用迭代器向vector插入数据时,要注意控制迭代器的位置,直接插入,程序会直接崩溃。
下面用代码解释这个问题。
#include <iostream>
#include <vector>
using namespace std;
//元素值与3取余是0时插入一个数字
void VectorInsert(){
vector<int> v{1,2,3,4,5,7,8,9};
auto it=v.begin();
int cnt=0;
while(it != v.end()){
if((*it)%3==0){
it=v.insert(it, (*it)+100);
++it; //控制迭代器位置,这一步很关键
}
++it;
cnt++;
if(cnt>20){
break;
}
}
for (int n:v){
cout<<n<<endl;
}
}
void WrongInsert(){
vector<int> v{1,2,3,4,5,7,8,9};
for(auto it=v.begin();it != v.end();it++){
if((*it)%3==0){
v.insert(it, *it+20);
}
}
for (int n:v){
cout<<n<<endl;
}
}
int main(int argc, const char * argv[]) {
VectorInsert();
cout<<"-----------"<<endl;
//WrongInsert();直接崩溃
cout << "Hello, World!\n";
return 0;
}