tags:

views:

111

answers:

2

is it possible to iterate through until the end of list in main() function using the const_iterator? I tried using iter->end() but i can't figure it out.

#include <list>
#include <string>
using std::list;
using std::string;

class list_return
{
public:
list <string>::const_iterator get_list()
{
_list.push_back("1");
_list.push_back("2");
_list.push_back("3");
return _list.begin();
 }
 private:
list <string> _list;
};

int main()  
{  
   list_return lr;

   list <string>::const_iterator iter = lr.get_list();

   //here, increment the iterator until end of list

return 0;
}
A: 

There is no automatic way to know the end of the list given an iterator. You need a function which returns the end of the list. You can provide something like like const_iterator get_list_end().

Naveen
+4  A: 

You seem to have 'encapsulated' the list without exposing a way to access the end() method of the list which you need for your iteration to know when to finish. If you add a method that returns _list.end() to your list_return class (I've called it get_list_end) you could do something like this:

for (std::list<std::string>::const_iterator iter = lr.get_list();
        iter != lr.get_list_end();
        ++iter)
{
    //... 
}
Charles Bailey