C++ STL中Vector的游标会在插入或删除后失效
C++的STL中的Vector是很好用的一种数据结构,因为懒得写链表,前两天用它来实现用de Casteljau算法画Bezier曲线,这是实验作业。其间需要像Vector容器中插入元素,由于不知道游标在插入和删除后会失效,结果搞了很久才找出问题,记录一下。
直接说不直观,用一道小题来解释,对于数组1,3,5,7,9先用它们建立起一个vector,然后在它们两两之间插入它们相邻的整数。程序:
#include <iostream>
#include <vector>
using namespace std;
void show(vector<int> &v)
{ for(vector<int>::iterator iter=v.begin(); iter!=v.end(); ++iter) cout<<*iter<<' '; cout<<endl;
}
int main()
{ int a[]={1,3,5,7,9}; vector<int> v(a,a+sizeof(a)/sizeof(int)); show(v); //show 1 3 5 7 9
for(vector<int>::iterator iter=v.begin()+1; iter!=v.end(); iter+=2) iter=v.insert(iter,*iter-1); //Correct. //v.insert(iter,*iter-1); //Wrong,iter is invalid now. show(v); //show 1 2 3 4 5 6 7 8 9
return 0;
}
正如程序中注释的,vector的插入和删除都会返回一个新的游标,它指向新插入的值,该值在原来游标指向的值的前面。删除则指向原来的值的后面,所以当删除最后一个值时,小心。
转载请注明:来自pugWoo's Life
本文地址:http://www.pugwoo.com/2009/11/20/stl-vector-iter-invalid.html
16 条评论
我要留言mulberry outlet 发表于 2011-11-22 at 16:36 回复 引用
christian louboutin replica high heels in our online uk store. Your shoes sales prices will save. Christian Louboutin Knockoffs shoes sale now, newest styles of christian louboutin high heels in hot sale now. Welcome to purchase!
cheap ugg boots 发表于 2011-11-29 at 11:34 回复 引用
Ray Ban Aviator 发表于 2011-12-08 at 12:25 回复 引用
beats studio 发表于 2011-12-26 at 15:01 回复 引用
burberry handbags 发表于 2011-12-26 at 15:01 回复 引用
cheap ray ban sungla 发表于 2011-12-26 at 15:01 回复 引用
sac longchamp pas ch 发表于 2012-01-13 at 16:18 回复 引用
les incertitudes liées à la double menace de prolifération nucléaire
好
casque dr dree 发表于 2012-01-13 at 16:19 回复 引用
chanel bag 发表于 2012-01-13 at 16:19 回复 引用
coach online outlet 发表于 2012-01-20 at 13:33 回复 引用
burberry outlet 发表于 2012-01-20 at 13:33 回复 引用
beats by dre discoun 发表于 2012-01-20 at 13:34 回复 引用