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

本文解析了C++中list和forward_list的迭代器为何不支持加减运算的原因,并提供了示例代码展示这些限制如何在实践中表现出来。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>’)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值