What is the most painless approach to insert an element in the middle of std :: vector

I want to be able to insert an element in the middle (or another place) in a vector without overwriting the existing element.

Say that my vector has 3 6 9 10, and I want to insert 7 right after 6. How can I do this without causing problems? This is a very rare operation, so effectiveness is not a problem here. In addition, at the moment I can not switch to another container (for example: std :: list), which is good for inserts in the middle.

Will the std::insertvector do what I want? How?

thanks

+3
source share
6 answers

For this operation exists vector::insert.

iterator insert(
   iterator _Where,
   const Type& _Val
);
void insert(
   iterator _Where,
   size_type _Count,
   const Type& _Val
);
+11

, "7" "6", , .

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
+7

vector::find, vector::insert, , :

std::vector<int> v;
v.push_back(3);
v.push_back(6);
v.push_back(9);
v.push_back(10);
std::vector<int>::iterator pos = std::find(v.begin(),v.end(), 6);
v.insert(pos, 7);
+2

, , :

std::vector<int> v;
v.push_back(3);
v.push_back(6);
v.push_back(9);
v.push_back(10);

std::insert(std::upper_bound(v.begin(), v.end(), 7), 7);
+2

, .

+1

The sample Mash code matches the dot (but be careful that it inserts where you expect with an odd size). In addition, although you said that efficiency is not a problem, you might consider using the vector reserve () function to avoid redistribution and hidden copying. (β€œDon't pessimize prematurely,” as Sutter and Alexandrescu say in the Coding Standards Standards.)

+1
source

Source: https://habr.com/ru/post/1721795/


All Articles