vector的iterator的错误使用

本文讨论了C++标准库中vector迭代器的一个特殊问题,即通常不能对临时迭代器进行增量和减量操作。这是因为vector迭代器通常实现为普通指针,而对临时值的指针修改是不允许的。尽管此问题在编译时就能发现,避免意外行为,但它可能浪费开发者的时间。对于字符串迭代器,也存在相同问题,因为它们通常也是字符指针。使用deque、list、set和map等其他容器则不会遇到这个问题,因为它们的迭代器不能实现为普通指针。为确保代码可移植,建议避免直接使用++coll.begin()这样的写法。示例代码展示了如何使用iter_swap算法函数,但当容器为vector时,程序通常无法正常工作,因为vector的迭代器需要随机访问迭代器支持。
摘要由CSDN通过智能技术生成

原文如下:(摘自<<c++ standard library>>)

 

 

7.2.6 The Increment and Decrement Problem of Vector Iterators

The use of the increment and decrement operators of iterators includes a strange problem. In general, you can increment and decrement temporary iterators. However, for vectors and strings, you typically can't. Consider the following vector example:

					
   std::vector<int> coll;
   ...
   //sort, starting with the second element
   // - NONPORTABLE version 
   if (coll.size() > 1) {
       coll.sort (++coll.begin(), coll.end());
   }

				

Typically, the compilation of sort() fails. However, if you use, for example, a deque rather than a vector, it will compile. It might compile even with vectors, depending on the implementation of class vector.

The reason for this strange problem lie

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值