C++中list和forward_list的迭代器不支持加减运算
来源:互联网 发布:共青团网络志愿者 编辑:程序博客网 时间:2024/06/05 11:54
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>’)
阅读全文