您的位置:首页 > 编程语言 > C语言/C++

C++中list和forward_list的迭代器不支持加减运算

2017-12-25 09:58 337 查看
C++中list和forward_list的迭代器不支持加减运算,这是因为什么原因呢?

那是因为双向链表和单向链表存储元素都不是在一块连续的内存上,所以无法通过加减法远距离查找元素。

下面是测试源码:

#include<iostream>
#include<list>
#include<forward_list>

using namespace std;

int main(void)
{
list<int> lst1={1,5,7,10,15};
//forward_list<int> lst1={1,5,7,10,15};
auto plst1 = lst1.begin();
cout<<"*plst1:"<<*plst1<<endl;
cout<<"*(++plst1):"<<*(++plst1)<<endl;
//cout<<"*(plst1+1):"<<*(plst1+1)<<endl;
 //cout<<"*(--plst1):"<<*(--plst1)<<endl;

return 0;
}

 如果list和forward_list想用加减法就会报错    error: no match for ‘operator+’ (operand types are ‘std::_Fwd_list_iterator<int>’ and ‘int’)
而且forward_list是不支持--运算的,会报error: no match for ‘operator--’
(operand type is ‘std::_Fwd_list_iterator<int>’)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: