在std :: vector中间插入元素的最无痛方法是什么

veh*_*zzz 3 c++ stl

我希望能够在向量中间(或其他位置)插入元素而不覆盖现有元素.

假设我的矢量有3 6 9 10并且我想在6之后插入7.如何在不引起问题的情况下完成?这是非常罕见的操作,因此效率在这里不是问题.此外,此时,我无法切换到另一个容器(例如:std :: list),这些容器适用于中间的插入.

std::insert矢量中的意志会做我想要的吗?怎么样?

谢谢

Ale*_*tov 11

vector::insert这个操作.

iterator insert(
   iterator _Where,
   const Type& _Val
);
void insert(
   iterator _Where,
   size_type _Count,
   const Type& _Val
);
Run Code Online (Sandbox Code Playgroud)


irh*_*irh 7

我编辑了这个例子,在'6'之后直接插入'7',因为问题更多的是关于插入特定位置而不是任意地插入向量的中心.

std::vector<int> v;
v.push_back(3);
v.push_back(6);
v.push_back(9);
v.push_back(10);
std::vector<int>::iterator insert_pos = std::find(v.begin(), v.end(), 6);
// only increment iterator if we've found the insertion point,
// otherwise insert at the end of the vector
if (insert_pos != v.end()) {
    ++insert_pos;
}
v.insert(insert_pos, 7);
// v now contains 3, 6, 7, 9, 10
Run Code Online (Sandbox Code Playgroud)