Providing Iterators for 2 STL containers within a class

Hello,

I am trying to improve my knowledge on iterators, I think I have a decent understanding of their functionality as well as their benefits. I had a question on providing multiple iterators for a class, where each iterator iterates over a different member. Lets say we have the class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class My_Class
{
     public:
       My_Class()
       {...}

       ~My_Class()
       {...}


     private:
        typedef std::vector<int> int_data;
        int_data  my_ints;

        typedef std::vector<std::string> string_data
        string_data  my_strings;
}


If I want to provide iterators for this class, one for each of the two data members, what is a good way of doing this? I was thinking of defining,

1
2
3
4
5
6
7
typedef std::vector<int>::iterator int_iterator;
int_iterator begin() { return my_ints.begin(); }
int_iterator end() { return my_ints.end(); }

typedef std::vector<string>::iterator string_iterator;
string_iterator begin() { return my_strings.begin(); }
string_iterator end() { return my_strings.end(); }


but this doesn't seem to work. Any suggestions would be appreciated. thanks
Last edited on
You cannot define two function with same name and signature.

This cna be solved in multiple ways:
1) make each name distinct:
1
2
3
4
vector_begin();
vector_end();
string_begin();
string_end();

2) Provide direct access to containers so users can call needed functions manually or provide access to proxy classes providing only limited access to containers (so nobody will reassign, resize vectors or do something unexpected):
1
2
3
4
5
6
std::vector<int>& My_Class::vector();
//Or
My_Class::vector_proxy My_Class::vector();

My_Class foo;
foo.vector().begin();

This approach is good as it allows to use ranged for and many container functions on any subcontainer easily.
3) Do something else/change one of the previous approaches

Unless you want your class to be and threated as iteratable do not provide member function begin for it. (for example in your case it is unclear what vector should be accessed by default.)
Topic archived. No new replies allowed.