You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++不使用insert()向Vector插入元素时末尾元素丢失问题

问题描述

不使用C++ vector内置insert()方法实现元素插入功能时,执行插入操作后vector最后一个元素丢失,未按预期完成动态扩容、长度同步增加。
问题复现代码:

#include <vector>
#include <iostream>
#include <algorithm>   
using namespace std;
void display(vector<int> arr){
    cout<<"Result"<<endl;
    for(auto &p: arr){
        cout<<p<<endl;
    }
}
void indsert(vector<int> arr, int size, int element, int ind){
    for(int i=size+1; i>=ind; i--)
        arr[i] = arr[i-1];
    arr[ind] = element;
    display(arr);
}
int main()
{
    int ind,size,element;
    cout<<"Enter the size of the array"<<endl;
    cin>>size;
    vector<int> arr;
    cout<<"Enter the elements of the array"<<endl;
    for(int i=0;i<size;i++){
        int temp;
        cin>> temp;
        arr.push_back(temp);
    }
    cout<<"Enter the element to be inserted"<<endl;
    cin>>element;
    cout<<"Enter the index"<<endl;
    cin>>ind;
    indsert(arr, size, element, ind);
    
return 0;
}
故障原因
  • 参数传递方式错误:display和indsert函数的vector入参都是值传递,进入函数时会生成原vector的临时拷贝,所有修改都只作用在临时拷贝上,不会同步到原vector。
  • 内存越界访问:传入indsert的临时vector长度和原vector一致为size,合法下标范围是0 ~ size-1,循环从i=size+1开始赋值,直接访问了vector已分配内存范围外的地址,属于未定义行为。
  • 缺失扩容逻辑:整个插入流程没有主动增加vector的长度,vector本身不会因为超范围下标赋值就自动扩容,长度始终保持为插入前的size,根本没有空间存储多出来的新元素,自然会出现元素丢失的现象。
  • 循环边界错误:原循环终止条件设为i>=ind,会多移动一位元素,造成不必要的内存覆盖。
修复方法

按以下规则调整代码即可实现正确插入:

  1. 将两个函数的vector入参改为引用传递,消除不必要的临时拷贝,确保操作直接作用于目标vector;display函数不会修改vector内容,可以加const修饰更安全。
  2. 执行元素后移操作前,先调用push_back给vector追加一个占位元素,把vector长度+1,预留出插入新元素的空间,从根源避免越界访问。
  3. 调整元素后移的循环边界,从原vector的最后一个有效下标(即size-1位置,追加占位后对应下标size)开始向前遍历到插入位置的后一位,完成元素后移,避免过度移动覆盖数据。
  4. 可选增加插入索引合法性校验,拦截非法输入导致的越界问题。

修复后的完整可运行代码:

#include <vector>
#include <iostream>
using namespace std;

void display(const vector<int>& arr){
    cout<<"Result"<<endl;
    for(const auto &p: arr){
        cout<<p<<endl;
    }
}

void indsert(vector<int>& arr, int size, int element, int ind){
    // 追加占位元素,长度+1完成扩容
    arr.push_back(0);
    // 从尾部开始后移元素,避免提前覆盖数据
    for(int i = size; i > ind; i--){
        arr[i] = arr[i-1];
    }
    arr[ind] = element;
    display(arr);
}

int main()
{
    int ind,size,element;
    cout<<"Enter the size of the array"<<endl;
    cin>>size;
    vector<int> arr;
    cout<<"Enter the elements of the array"<<endl;
    for(int i=0;i<size;i++){
        int temp;
        cin>> temp;
        arr.push_back(temp);
    }
    cout<<"Enter the element to be inserted"<<endl;
    cin>>element;
    cout<<"Enter the index"<<endl;
    cin>>ind;
    // 索引合法性校验
    if(ind < 0 || ind > size){
        cout<<"Invalid insert index!"<<endl;
        return 1;
    }
    indsert(arr, size, element, ind);
    return 0;
}

内容的提问来源于stack exchange,提问作者Anirban Saha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 18:24:32