我需要使用C ++遍历列表的示例。
答案 0 :(得分:32)
您的问题的示例如下
#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;
}
答案 1 :(得分:19)
要反映C ++中的新增内容并通过@karthik扩展有些过时的解决方案,starting from C++11 it can be done shorter使用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 << " ";
}
或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 << " ";
}
答案 2 :(得分:7)
如果您的意思是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;
}
答案 3 :(得分: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;
}