我需要使用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 << " ";
}
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
。 - Mike Seymour现在你可以直接使用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;
}