开发者

Iterating the std::list through a const_iterator

开发者 https://www.devze.com 2022-12-18 03:36 出处:网络
is it possible to iterate through until the end of list in main() function using the const_iter开发者_C百科ator? I tried using iter->end() but i can\'t figure it out.

is it possible to iterate through until the end of list in main() function using the const_iter开发者_C百科ator? 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().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号