首页 > 解决方案 > 可以乱序插入向量吗?

问题描述

我想vec1通过vec2and插入vec3。当我vec3先插入时,程序无法成功退出。但是当我 insertvec2然后 insertvec3时,程序可以成功退出。我想知道失败的原因。

为什么插入vec1 乱序:我想通过两个不同的线程插入(两个线程会写入不同的位置,互不影响),所以不能保证顺序。

#include <iostream>
#include <vector>
#include <chrono>

using namespace std::chrono;
using namespace std;


struct DocIdAndPayLoad
{

    uint64_t m_docId;

    DocIdAndPayLoad()
    {
        DefaultCnt++;
    }


    DocIdAndPayLoad(const DocIdAndPayLoad& /*_bond_rhs*/)
    {
        CopyCnt++;
    }


    DocIdAndPayLoad(DocIdAndPayLoad&& _bond_rhs)
    {
        MoveCnt++;
    }


    DocIdAndPayLoad& operator=(const DocIdAndPayLoad& _bond_rhs)
    {
        AssignCnt++;
        return *this;
    }


    static int DefaultCnt;
    static int CopyCnt;
    static int MoveCnt;
    static int AssignCnt;
};

int DocIdAndPayLoad::DefaultCnt = 0;
int DocIdAndPayLoad::CopyCnt = 0;
int DocIdAndPayLoad::MoveCnt = 0;
int DocIdAndPayLoad::AssignCnt = 0;

int main()
{
    const int hugeSize=10000;
    vector<DocIdAndPayLoad> vec1;
    cout<<vec1.size()<<" "<<vec1.capacity()<<endl;

    vector<DocIdAndPayLoad> vec2(hugeSize/2);
    vector<DocIdAndPayLoad> vec3(hugeSize/2);

    auto start1 = high_resolution_clock::now();
    vec1.reserve(hugeSize);
    
    //vec1.insert(vec1.begin()+hugeSize/2, std::make_move_iterator(vec3.begin()), std::make_move_iterator(vec3.end()));
    vec1.insert(vec1.begin(), std::make_move_iterator(vec2.begin()), std::make_move_iterator(vec2.end()));
    
    auto stop1 = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop1 - start1);
    cout << "Cost1: "<< duration.count() << " microseconds" << endl;

    vector<DocIdAndPayLoad> vec4;
    auto start2 = high_resolution_clock::now();
    vec4.resize(hugeSize);
    auto stop2 = high_resolution_clock::now();
    auto duration2 = duration_cast<microseconds>(stop2 - start2);
    cout << "Cost2: "<< duration2.count() << " microseconds" << endl;

    cout<<vec1.size()<<" "<<vec1.capacity()<<endl;
         
    return 0;
}


标签: c++vectorstl

解决方案


reserve调用设置向量的容量,但不设置其大小。这意味着调用后向量仍然为空

vec1.reserve(hugeSize);

该向量中的任何索引都将超出范围并导致未定义的行为。

更重要的是,由于向量为空,vec1.begin()会返回结束迭代器(即vec1.begin() == vec1.end()),所以vec1.begin()+hugeSize/2无效.

尝试取消引用end迭代器(或超出)会导致未定义的行为和可能的崩溃。


推荐阅读