Home > front end >  Inserting an element in given positions (more than one) of a vector
Inserting an element in given positions (more than one) of a vector

Time:03-01

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

  • the value is 11 and hence local_index = 11
  • The vector of position I have in input is neigh = {5,7}
  • The starting vector is Col={0,1,2,3,4,5,6,7,8,9,10}

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:

  • Is this because the insert return a pointer that cannot be re-assigned?
  • If the answer to the first question is yes, how can I achieve my goal?

CodePudding user response:

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);
  • Related