C++ Vector資料插入
用迭代器向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;
}
相關文章
- vector——C++C++
- C++ sort vector<vector<int> > or vector<MyClass> 容器的排序C++排序
- C++ STL -- vectorC++
- C++ Vector fundamentalC++
- C++ folly庫解讀(二) small_vector —— 小資料集下的std::vector替代方案C++
- mybatis插入資料、批量插入資料MyBatis
- C++的vector容器C++
- C++之vector容器C++
- C++:vector assignC++
- C++中vector*和vector有什麼區別C++
- c++ vector用法詳解C++
- C++【vector】用法和例子C++
- C++ 容器vector的使用C++
- c++ std::vector 切記C++
- C++ STL學習——vectorC++
- c++ vector刪除元素C++
- C++中vector<int>& numsC++
- mongodb 插入資料MongoDB
- c/c++ 標準庫 vectorC++
- C++ ——vector陣列筆記C++陣列筆記
- C++ vector容器的swap方法C++
- C++學習之路(vector::clear和vector::erase的區別)C++
- 資料結構學習(C++)續——排序【2】插入排序 (轉)資料結構C++排序
- mongodb資料庫中插入資料MongoDB資料庫
- c++中stack、queue、vector的用法C++
- oracle批量插入資料Oracle
- [MYSQL -19]插入資料MySql
- MyBatis 批量插入資料MyBatis
- 資料插入問題。
- Oracle 插入大量資料Oracle
- append插入不能多次未提交插入資料APP
- proc插入資料到資料庫資料庫
- oracle 大資料量資料插入Oracle大資料
- ColdFusion向資料庫插入資料例子資料庫
- mysql插入資料時如果有相同資料就不插入或者替換MySql
- 自己動手寫Vector【Cherno C++教程】C++
- 【C++學習筆記】vector和arrayC++筆記
- C++ Vector遍歷的幾種方式()C++