简体   繁体   中英

Iterating the std::list through a const_iterator

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;
}

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)
{
    //... 
}

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM