简体   繁体   English

通过const_iterator迭代std :: list

[英]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? 是否可以使用const_iterator遍历main()函数中的列表末尾? I tried using iter->end() but i can't figure it out. 我尝试使用iter-> end(),但我无法弄清楚。

#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. 您似乎已经“封装”了列表,但没有提供访问列表的end()方法的方法,您的迭代过程需要知道该方法何时完成。 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: 如果添加将_list.end()返回到list_return类的方法(我将其称为get_list_end),则可以执行以下操作:

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() . 您可以提供类似const_iterator get_list_end()类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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