vector的iterator的错误使用

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

原文如下:(摘自<<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 lies in the fact that vector iterators are typically implemented as ordinary pointers. And for all fundamental data types, such as pointers, you are not allowed to modify temporary values. For structures and classes, however, it is allowed. Thus, if the iterator is implemented as an ordinary pointer, the compilation fails; if implemented as a class, it succeeds. It always works with deques, lists, sets, and maps because you can't implement iterators as ordinary pointers for them. But for vectors, whether it works depends on the implementation. Usually, ordinary pointers are used. But if, for example, you use a "safe version" of the STL, the iterators are implemented as classes. To make your code portable you should not code as the previous example, using vectors. Instead, you should use an auxiliary object:

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

				

The problem is not as bad as it sounds. You can't get unexpected behavior because it is detected at compile time. But it is tricky enough to spend time solving it. This problem also applies to strings. String iterators are usually also implemented as ordinary character pointers, although this is not required.

 

 

意思是说vector里面的iterator实际上是个指针类型。所以,coll.begin()返回的是容器存储的首个元素的地址,也就返回了一个指针的值,所以不能对其进行++coll.begin()操作。而通过std::vector<int>::iterator beg另外定义一个变量后,就可以对其进行++beg操作了。

 

如果不是vector,而是list,由于list里面的iterator是一个类,所以可以用list mylist; ++mylist.being()操作。但是sort支持的是randomaccess iterator,所以,不能在sort里使用list的iterator作为参数。下面用iter_swap算法函数演示:

 

 

 #include <iostream>
   #include <list>
   #include <algorithm>
   #include "print.hpp"
   using namespace std;


   int main() 
   {
       list<int> coll;


       //insert elements from 1 to 9
       for (int i=1; i<=9; ++i) {
           coll.push_back(i); 
       }


       PRINT_ELEMENTS(coll);


       //swap first and second value
       iter_swap (coll.begin(), ++coll.begin());


       PRINT_ELEMENTS(coll);


       //swap first and last value
       iter_swap (coll.begin(), --coll.end());

       PRINT_ELEMENTS(coll);
   }

				

The output of the program is as follows:

					
   1 2 3 4 5 6 7 8 9
   2 1 3 4 5 6 7 8 9
   9 1 3 4 5 6 7 8 2

 

 

Note that this program normally does not work if you use a vector as a container. This is because ++coll.begin() and --coll.end() yield temporary pointers (see Section 7.2.6, for details regarding this problem).

 

C++ 使用vector 出现"vector iterator not incrementable"或"vector iterator + offset out of range"错误的情况 测试代码1:  vector g_vtStr1; vector g_vtStr2; vector g_vtStr3;   g_vtStr1.push_back(_T("Test1"));     g_vtStr1.push_back(_T("Test2"));     g_vtStr1.push_back(_T("Test3"));     g_vtStr1.push_ba 阅读详情

相关推荐

iterator not dereferencable问题

STL中的迭代器总是出现各种问题,这个是我在打表达式求值时碰到的... 综合网上的答案,一般来说有两种情况: 第一:访问了非法位置。 一般来说可能在queue为空时取front(),rear(),或者用list时误访最后一个结点,再或是在stack为空时进行了top(),pop()操作等。 一般来说用一下方法解决即可: (1)在访问链表元素时判断当前迭代器是否指向链表尾 1 li...

weixin_30906185的博客 846

Debug Assertion Failed ! List iterator not dereferencable

代码如下 #include #include #include #include #include typedef std::list lisInt; void Print(lisInt L, lisInt P); const int LIMIT{ 100 }; int main() { /*Creat a random list*/ lisInt List1; srand(ti

onlyuyuns的博客 1118

有关提示vector iterator not dereferencable的问题

关于C+ #include #include using namespace std; //判断两个vector是否相等 //使用迭代器访问vector中的元素 int main() { vector ivec1,ivec2; int ival; //读入两个vector的元素值 cout cin>>ival; while(ival!=-1){

liqiuqium11的专栏 1万+

vector iterator not derefencable错误

刚刚解决了一个vector iterator not derefencable断言错误。 原来错误处在我往vector塞的是int,但是在另一个函数里却把这个vector当做vector &v,类型不匹配。 inline bool isElemtInVector(vector &v,const unsigned char e) { vector::iterator it; for(it=v

super_fish的专栏 1766

vector iterator not incrementable(不明显的错误

使用vector中报出这样的错误,网上查说是迭代器删除的问题,一直没找到原因,后来终于想明白了。做个笔记,希望给遇到同样问题的读者留个参考。 1.出问题代码是这个样子的 for (auto iter = MouseListeners.v.begin(); iter != MouseListeners.v.end();++ iter) { (*iter)-...

会飞的徐公明 1789

"vector iterator incompatible"错误!!!

这是在new company里记录的第一篇blog.这个问题足足让费了2个小时去调试,代价太大! //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  问题描述:           clas

wu_123_456的专栏 1313

在用vector 迭代器遇到“vector iterator not incrementable”错误解决办法

1.使用vector的迭代器erase元素的时候,应该注意迭代器越界的问题,eg:   for ( auto it = vec.begin();  it != vec.end();  ++it ){ if ( *it == 2 )  vec.erase(it); } 这样操作会报错“vector iterator not incrementable”; 原因:在执行完era

sun小武 3759

vector iterator not incrementable错误解决

原出处:http://www.cnblogs.com/azor/p/3591062.html 2014/03/11更新:循环删除容器中符合条件的元素   《C++ Primer(Edit 5)》, P.349   Both forms of erase return an iterator referring to the location after the(last)

ss_shine6的博客 1177

Linux中编译错误之——‘need ‘typename’ before ‘std::vector<T>::const_iterator’ because ‘std::vector<T>’ is a‘

Linux中编译错误之——need ‘typename’ before ‘std::vector::const_iterator’ because ‘std::vector’ is a dependent scope(题目只有100的限制) C++编译.cpp文件,出现错误vector.cpp: In function ‘void PrintVector(const std::vector<T>&)’: vector.cpp:23:3: error: need ‘typename’

weixin_41446512的博客 1350

istream_iterator常见的错误说明

istream_iterator使用中常见的错误说明(转载请注明来源于金庆的专栏)在http://www.cppblog.com/hdqqq/archive/2007/12/11/38216.html的评论中看到一段istream_iterator使用代码,读取文件test.txt,将其中字符串输入到一个vector。1. 错误原码以下原代码不能通过编译:    ifstream

金庆的专栏 3717

Vector pop_back

自己今天碰到的问题:typedef struct ReadFileOffsettag{            int  time;            LONG offset;}ReadOffset;  vector StoreEachReadInfoVec (第一种方法)vector ::iterator iter,iend; //起始和末尾迭代器值ie

7054

c++中vector向量的一些主要问题

近日,用到c++ STL中vector,浏览到关于出现 “_DEBUG_ERROR("vector iterator not dereferencable") “问题的一帖子: C++标准库assign()   链接:http://wenwen.soso.com/z/q165763904.htm 该帖子上的问题与我出现的问题相符,所以进一步进行了跟踪。引用该帖子中部分代码如下:

feixuedudiao的专栏 2037

vector类型的常对象与iterator常对象的对应使用

<br />//出现error C2440<br />bool is_equal( const vector <int> &ivec )  //vector对象的常引用<br />{<br />     forvector <int>::iterator it = ivec.begin() ;it != ivec.end() ;++it )  //这里使用的是iterator<br />       {<br />            ……<br />        }<br />}<br /><br

Yang_Seal的专栏 1115

关于在vs2013中的一个错误

原来的代码是:vector vec1(0.1,0.1); vector vec2(0.2,0.2); 两句话出现了26个错误错误    10    error C2868:std::iterator_traits::value_type”: 非法的 using 声明语法;应输入限定名    d:\program files\vs\vc\include\xutility    3

ddsszzy的专栏 3804

const_iterator简单介绍

如果遇到常量容器类型,需要使用迭代器的时候,那么必须使用常量迭代器——const_iterator #include <iostream> #include <string> #include <vector> #include <deque> #include <list> #include <forward_list> #include <string> #include <array> using na

digitalkee的博客 2036

记录 错误 C7510 “iterator: 类型 从属名称的使用必须以“typename”为前缀 KMatrix_vector

1. 问题 “iterator: 类型 从属名称的使用必须以“typename”为前缀 今天将我VS2017 的代码移植到VS2019上面时,产生了上面的错误,产生错误的代码片段如下 vector<vector<T>>::iterator it = r.begin() + row; r.erase(it); rowCount--; 2. 解决办法 在vector前面加上 typename 解决问题,编译通过,还有其他人说改vs版本啥的方法,大家可以自己去百度一下,我

qq_43341440的博客 714
上一篇: MsgWaitForMultipleObjects + TranslateMessage 调用时要小心。
下一篇: 用了双缓冲绘图还闪烁
begges
博客等级 码龄20年 6粉丝 39原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值