albiremo
albiremo

Reputation: 207

Inserting an element in given positions (more than one) of a vector

I am trying to add a certain value in loop to a given position of a certain vector. For example:

I want to have as output Col={0,1,2,3,4,5,11,6,7,11,8,9,10}. This is my first try:

vector<long> neigh = {5,7};
long local_index = 11;
auto pos_col = Col.begin();
for (const auto& elem: neigh) {
        Col.insert(pos_col+elem,local_index);

I keep getting for the second value of neigh a segmentation fault. So my questions are:

Upvotes: 1

Views: 60

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596256

Per the vector::insert() documentation on cppreference.com:

Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.

Which means that, after your 1st call to insert(), your pos_col iterator is now invalid for subsequent calls to insert(), as it refers to an element before the insertion point.

Try using this instead:

auto pos_col = Col.begin();
for (const auto& elem: neigh) {
    Col.insert(pos_col+elem,local_index);
    pos_col = Col.begin();
}

Or simply:

Col.insert(Col.begin()+elem,local_index);

Upvotes: 4

Related Questions