Reputation: 207
I am trying to add a certain value in loop to a given position of a certain vector. For example:
local_index = 11
neigh = {5,7}
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:
Upvotes: 1
Views: 60
Reputation: 596256
Per the vector::insert()
documentation on cppreference.com:
Causes reallocation if the new
size()
is greater than the oldcapacity()
. If the newsize()
is greater thancapacity()
, 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