Inserting elements

suggest change

Appending an element at the end of a vector (by copying/moving):

struct Point {
  double x, y;
  Point(double x, double y) : x(x), y(y) {}
};
std::vector<Point> v;
Point p(10.0, 2.0);
v.push_back(p);  // p is copied into the vector.

Appending an element at the end of a vector by constructing the element in place:

std::vector<Point> v;
v.emplace_back(10.0, 2.0); // The arguments are passed to the constructor of the
                           // given type (here Point). The object is constructed
                           // in the vector, avoiding a copy.

Note that std::vector does not have a push_front() member function due to performance reasons. Adding an element at the beginning causes all existing elements in the vector to be moved. If you want to frequently insert elements at the beginning of your container, then you might want to use std::list or std::deque instead.

Inserting an element at any position of a vector:

std::vector<int> v{ 1, 2, 3 };
v.insert(v.begin(), 9);          // v now contains {9, 1, 2, 3}

Inserting an element at any position of a vector by constructing the element in place:

std::vector<int> v{ 1, 2, 3 };
v.emplace(v.begin()+1, 9);     // v now contains {1, 9, 2, 3}

Inserting another vector at any position of the vector:

std::vector<int> v(4);      // contains: 0, 0, 0, 0
std::vector<int> v2(2, 10); // contains: 10, 10
v.insert(v.begin()+2, v2.begin(), v2.end()); // contains: 0, 0, 10, 10, 0, 0

Inserting an array at any position of a vector:

std::vector<int> v(4); // contains: 0, 0, 0, 0
int a [] = {1, 2, 3}; // contains: 1, 2, 3
v.insert(v.begin()+1, a, a+sizeof(a)/sizeof(a[0])); // contains: 0, 1, 2, 3, 0, 0, 0

Use reserve() before inserting multiple elements if resulting vector size is known beforehand to avoid multiple reallocations (see vector size and capacity):

std::vector<int> v;
v.reserve(100);
for (int i = 0; i < 100; ++i) {
    v.emplace_back(i);
}

Be sure to not make the mistake of calling resize() in this case, or you will inadvertently create a vector with 200 elements where only the latter one hundred will have the value you intended.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::vector:
* Inserting elements

Table Of Contents
8 Arrays
11 Loops
23 std::vector
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype