我需要使用C++遍历列表的示例。使用迭代器遍历列表?
回答
有关问题的示例如下
#include <iostream>
#include <list>
using namespace std;
typedef list<int> IntegerList;
int main()
{
IntegerList intList;
for (int i = 1; i <= 10; ++i)
intList.push_back(i * 2);
for (IntegerList::const_iterator ci = intList.begin(); ci != intList.end(); ++ci)
cout << *ci << " ";
return 0;
}
简单的解决方案:http://www.java2s.com/Code/Cpp/List/TraverseaListUsinganIterator.htm – 2011-03-29 09:29:25
Omg,这是否值得被问及?哪里有参考? RTFM! – Viet 2017-05-02 20:55:58
如果你的意思是一个STL std::list
,那么这里就是从http://www.cplusplus.com/reference/stl/list/begin/一个简单的例子。
// list::begin
#include <iostream>
#include <list>
int main()
{
int myints[] = {75,23,65,42,13};
std::list<int> mylist (myints,myints+5);
std::cout << "mylist contains:";
for (std::list<int>::iterator it=mylist.begin(); it != mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
尽管如果你不需要修改列表,你应该使用'const_iterator'而不是'iterator'。 – 2011-03-29 10:11:03
迭代器是否从列表中删除元素并减小其大小? – Tariq 2015-02-17 16:11:27
@Tariq:迭代器_iterates_。 – 2016-08-02 00:55:38
要体现在C++中新增和@karthik,用auto符延长有些过时的解决方案starting from C++11 it can be done shorter:
#include <iostream>
#include <list>
using namespace std;
typedef list<int> IntegerList;
int main()
{
IntegerList intList;
for (int i=1; i<=10; ++i)
intList.push_back(i * 2);
for (auto ci = intList.begin(); ci != intList.end(); ++ci)
cout << *ci << " ";
}
或even easier使用range-based for loops:
#include <iostream>
#include <list>
using namespace std;
typedef list<int> IntegerList;
int main()
{
IntegerList intList;
for (int i=1; i<=10; ++i)
intList.push_back(i * 2);
for (int i : intList)
cout << i << " ";
}
- 1. 遍历列表的列表,并使用第i个迭代器
- 2. 使用s迭代器遍历映射列表
- 3. 迭代器中迭代遍历控件
- 4. Python Django模板:迭代遍历列表
- 5. 迭代遍历两个列表
- 6. DFS遍历迭代
- 7. 迭代Inorder遍历
- 8. 迭代遍历使用indexOf()的单个字符串列表()
- 9. 与多个迭代器同时遍历两个列表
- 10. 迭代反向序列遍历
- 11. itertools.groupby:迭代遍历组pairwise
- 12. 迭代遍历类Angular4
- 13. 迭代后序遍历bst?
- 14. 迭代DFS如何遍历?
- 15. 迭代八叉树遍历
- 16. libxmlrpc迭代遍历struct
- 17. 遍历列表使用JSON
- 18. 使用迭代器模式的n-tree树的预定/后序迭代遍历
- 19. 如何使用迭代遍历行和列来填充矩阵
- 20. Python:二叉树遍历迭代器不使用条件
- 21. 使用迭代器遍历boost :: ublas矩阵
- 22. 使用forEach和/或toArray遍历不同表的迭代命令
- 23. 遍历列表,如果满足条件,则可迭代打印
- 24. 同时遍历两个列表只迭代一次
- 25. 命名融合的迭代映射列表在遍历中
- 26. 迭代遍历列表后获取单个总和
- 27. 迭代遍历熊猫数据框列表的Matplotlib动画
- 28. 遍历列表
- 29. 遍历列表
- 30. 迭代子列表到列表中创建我要遍历子表字典
简单的解决方案在谷歌” ing:http://www.java2s.com/Code/Cpp/List/TraverseaListUsinganIterator.htm – 2011-03-29 09:29:54
“现在你只是懒惰懒惰”对于所有的w e知道海报可能是某种其他编程语言的专家。如果你不想帮助他,就不要。我3年后Google搜索,发现答案非常有用。 – 2014-01-27 18:34:45
为什么OP和同一个人接受的答案? – Viet 2017-05-02 20:56:35