(转http://hi.baidu.com/adoblog/blog/item/102574233779ba4a925807c0.html):Vector发现的一个使用细节:vector iterators incompatible
来源:互联网 发布:淘宝刷单后果是什么 编辑:程序博客网 时间:2024/05/16 19:22
以前使用VC6开发,最近换用VS2005编译以前的程序,在运行时出现断言,切回 调试器,发现提示是
"vector iterators incompatible”
发现引发这个错误的代码如下:
VectorType::iterator it = someVector.begin();
for (; it != someVector.end();)
{
if (*it== value)
{
someVector.erase(it);
}
else
{
++it;
}
}
代码中,在erase操作后,没有修改it就继续循环,在与end()比较时,断言出现。
这里的主要问题是,vector可以用任意方法实现erase,不保证在erase一个元素后,后续的元素一定被移动到这个iterator所引用的位置(地址)。当然,这在几乎所有STL的实现中,都是对的,这也就是以前用VC6编译后运行没有问题的原因。但如果这里用的不是vector,而是list或是map,运行到这里,程序会毫不犹豫的崩溃。
正确的做法是这样的:
STL里所有的容器类的erase实现都会返回一个iterator,这个iterator指向了“当前删除元素的后继元素,或是end()”
因此,在遍历容器的所有元素过程中通过erase删除一个元素后,将erase的返回值赋给迭代变量:
VectorType::iterator it = someVector.begin();
for (; it != someVector.end();)
{
if (*it== value)
{
it = someVector.erase(it);
}
else
{
++it;
}
}
P.S. 可以看出,VS2005带的STL增加了更多的调试特性以避免出现STL的一些错误,有条件的话最好用VS2005的STL。如果没有VS2005,也可以使用STLport,STLport在调试特性上也非常出色。
今天程序老崩溃,一开始以为是结构体数据元素过多,原来是STL的差异性引起的,记住这次的教训.
- (转http://hi.baidu.com/adoblog/blog/item/102574233779ba4a925807c0.html):Vector发现的一个使用细节:vector iterators incompatible
- Vector发现的一个使用细节:vector iterators incompatible(转)
- gcov lcov的使用http://hi.baidu.com/gtfcugb/blog/item/cf18d97b6ff161f20bd187ea.html
- Native SQL查询 (使用SQLQuery) (转http://hi.baidu.com/ufeiying/blog/item/420367237fc9dd5a9822ed8a.html)
- 必须掌握的八个cmd 命令行(转http://hi.baidu.com/chenleibupt/blog/item/d7006f861762663b66096e27.html)
- 转来的文章:http://hi.baidu.com/qinuo5277/blog/item/ba87ac0838205b39e92488ae.html
- struts2的配置详解(转自 http://hi.baidu.com/louhu/blog/item/52d2d1652bbeccfaf6365458.html)
- 配置安全的ssh服务器(转:http://hi.baidu.com/9812658/blog/item/32d3a8d37c9bd4d8572c8413.html)
- 关于sqlite3的性能(转自:http://hi.baidu.com/snailzone/blog/item/da9368662bc94f25aa184c2b.html)
- 会说话的猪 转自:http://hi.baidu.com/gg81/blog/item/91c088ef5b177114fdfa3c72.html
- http://hi.baidu.com/heyg/blog/item/9ca8dcc4785706cb38db4937.html
- http://hi.baidu.com/suwey/blog/item/9b4d72c238e7e334e5dd3bc0.html
- http://hi.baidu.com/lhcling/blog/item/0e3e60cfa55aca3ef8dc61c0.html
- http://hi.baidu.com/jmugis/blog/item/ad03b11f89a25ef6e1fe0b18.html
- http://hi.baidu.com/nnffnn/blog/item/e84cd15c1d893943faf2c07c.html
- http://hi.baidu.com/herowzz/blog/item/286e3c546eb23157574e0077.html
- http://hi.baidu.com/kacaca/blog/item/1fd412d644f9f42907088b89.html
- http://hi.baidu.com/sophie198384/blog/item/26960501e9a757021d9583a0.html
- 定制TextBox文本框
- c语言中的符号解析
- 编译TortoiseSVN项目version.h找不到的问题
- 寻找第k小的元素C语言
- Ural 1018. A Binary Apple Tree
- (转http://hi.baidu.com/adoblog/blog/item/102574233779ba4a925807c0.html):Vector发现的一个使用细节:vector iterators incompatible
- 2010上海工博会上的宜科展台
- vim基本使用方法
- RHEL6-易用的防火墙配置工具
- Project2--Lucene的Ranking机制浅析
- 横竖屏切换测试
- Javascript实例:Select的OnChange()事件
- Android中字体的处理
- NSURLConnection同步与异步请求