C++std容器list遍历为什么可以用迭代器自加++

很多初学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;
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值