[英]Can insert into vector Out of order?
我想通过vec2
和vec3
vec1
当我先插入vec3
时,程序无法成功退出。 但是当我插入vec2
再插入vec3
时,程序可以成功退出。 我想知道失败的原因。
为什么插入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;
}
reserve
调用设置向量的容量,但不设置其大小。 这意味着调用后向量仍然为空
vec1.reserve(hugeSize);
该向量中的任何索引都将超出范围并导致未定义的行为。
更重要的是,由于向量为空, vec1.begin()
将返回结束迭代器(即vec1.begin() == vec1.end()
),所以vec1.begin()+hugeSize/2
无效! .
尝试取消引用end
迭代器(或超出)会导致未定义的行为和可能的崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.