Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Insertion into Vector - after or before iterator?

Context is: dataset of unknown size which gets iterated over constantly but has minimal insertions after initialisation (speed at initialisation not a concern).

Confusion is over element position after insertion into vector:

If we insert at vector.begin() when the vector is empty, it creates an element at the address .begin().

If we insert at vector.begin() when the vector is Not Empty, does it move the existing element at .begin() forward one, or does it place the new element after .begin()?

Similarly, if iterating over a vector and matching for a specific condition in the vector elements before inserting the new element, if we insert as follows: vector.insert(iterator, new_element)

does it insert the element after the current iterated element, or before it? Thanks in advance. M

like image 422
metamorphosis Avatar asked Apr 13 '14 01:04

metamorphosis


1 Answers

Quoting cppreference on std::vector::insert():

inserts value before the location pointed to by [iterator].

We need a single syntax to insert at every possible position (start, end, somewhere between these two):

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

The end pointer of a container is a point after the last element, we can't insert past that point, so we insert before.

Also when the container is empty, std::begin(container) == std::end(container) is true, so insert(std::begin(container), value) will work.

like image 103
Chnossos Avatar answered Sep 17 '22 19:09

Chnossos