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;
}

 

C++中,`vector`是标准模板库(STL)中的一个动态数组容器,它允许在序列的任何位置快速插入新元素。以下是几种在`vector`中插入数据的方法: 1. 使用`push_back()`函数在`vector`的末尾插入一个元素。这个函数会自动将元素添加到`vector`的末尾,并且如果需要,`vector`会进行扩容操作。 ```cpp std::vector<int> vec; vec.push_back(10); // 在vector末尾插入元素10 ``` 2. 使用`insert()`函数在`vector`的指定位置插入一个或多个相同的元素,或者插入一个范围内的元素。 - 插入单个元素: ```cpp vec.insert(vec.begin() + 5, 20); // 在vector的第5个位置(从0开始计数)插入元素20 ``` - 插入多个相同的元素: ```cpp vec.insert(vec.begin() + 5, 3, 30); // 在vector的第5个位置插入3个元素30 ``` - 插入另一个容器中的所有元素: ```cpp std::vector<int> anotherVec = {40, 50, 60}; vec.insert(vec.begin() + 5, anotherVec.begin(), anotherVec.end()); // 在vector的第5个位置插入anotherVec中的所有元素 ``` 3. 使用`emplace`函数在`vector`的指定位置直接构造一个新元素。这个方法的优势在于它可以直接在`vector`内部构造对象,避免了不必要的拷贝或移动操作。 ```cpp vec.emplace(vec.begin() + 5, 70); // 在vector的第5个位置直接构造元素70 ``` 请注意,使用`insert()`和`emplace()`函数插入元素时,如果指定的位置超出了当前`vector`的大小,新插入的元素将会被添加到`vector`末尾。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值