很多初学list会感到疑惑,都说list物理存储上是不具有逻辑性的,即不能通过iter += i;进行对第i个元素的访问。
但是我们能看到以下代码可以运行:
一
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> l1;
list<int> l2(2,0);
list<int>::iterator iter;
l1.push_back(1);
l1.push_back(2);
l2.push_back(3);
for(iter = l1.begin() ; iter != l1.end() ; iter++)//此处的++已经被重载了, 这就是为什么定义迭代器时不同的容器需要不同的说明,此处的++并不等于+= ,并且只能用++,用+=2或者其他会编译错误
{
cout<<*iter<<" ";
}
cout<<endl<<endl;
return 0;
}
输出如下:
二
#include<stdio.h>
#include<iostream>
#include<list>
#include<string>
#include<algorithm>
using namespace std;
void PrintIt(string& StringToPoint)
{
cout << StringToPoint << endl;
}
int main()
{
list<string> test;
list<string>::iterator testiterator;
test.push_back("no");
test.push_back("march");
test.push_front("ok");
test.push_front("loleina");
test.push_front("begin");
test.push_back("end");
for (testiterator = test.begin(); testiterator != test.end(); ++testiterator)
{
cout << *testiterator << endl;
}
cout << "-------------" << endl;
for_each(test.begin(), test.end(), PrintIt);
cout << "-------------" << endl;
system("PAUSE");
return 0;
}
运行结果同样是全部输出,且无误:
原因:
此处的**++已经被重载**了, 这就是为什么定义迭代器时不同的容器需要不同的说明,此处的++并不等于+= ,所以list的迭代器不能用原生指针(即普通指针)去模拟实现
百度百科另一种说法:
1、std::list是顺序容器,但不是随机访问容器(仅有std::vector,C数组和c++11中的std::array是),所以其迭代器只支持++和–这种双向的链式操作(c++11中的slist则只支持++)。
2、如果想一次移动多个位置,也可以使用里的advance函数,例子如下:
list<int>::iterator it = mylist.begin();
advance (it,5);
cout << "The sixth element in mylist is: " << *it << endl;