我需要使用 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;
}
为了反映 C++ 中的新添加内容并扩展@karthik 有点过时的解决方案,从 C++11 开始,可以使用 auto 说明符来缩短:
#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 << " ";
}
或者更容易使用基于范围的for循环:
#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 << " ";
}
如果您指的是 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;
}
现在你可以使用this:
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> intList;
for (int i = 1; i <= 10; ++i)
intList.push_back(i * 2);
for (auto i:intList)
cout << i << " ";
return 0;
}
这里我使用
while
来遍历,使用 next
来递增迭代器
#include <iostream>
#include<list>
int main() {
std::list<int> nums({1,2,3,4,5,6,7,8,9});
std::list<int>::iterator it = nums.begin();
while (it != nums.end()) {
std::cout << *it <<std::endl;
it = next(it,1);
}
return 0;
}