#include <vector>
#include <algorithm>
#include <iostream>
int main(){
std::vector<int> vec{0, 1, 2};
std::vector<int>::iterator it = std::max_element(vec.begin(), vec.end());
std::vector<int> vec2{3, 4, 5};
vec.insert(vec.end(), vec2.begin(), vec2.end());
vec.erase(it);
for (auto &n : vec){
std::cout << n << std::endl;
}
}
but when i execute it, I get this output:
1
2
3
4
5
double free or corruption (out)
Aborted
first question: why this corruption error and how to fix it?
second: why is the output "1 - 2 - 3 - 4 - 5", and not "0 - 1 - 3 - 4 - 5"!? since the iterator "it" points to the max value in vec, I would expect to value 2 being erased, not 0.
I'm using g++ (Debian 9.2.1-8) 9.2.1 20190909
and for some reason, if I execute this code online (in cpp.sh), I get no errors about memory corruption, but the output is still wrong.
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.
Use std::distance as coder777 said, or, simply move line 10 above line 9.
Keeping references to an element of a vector that is changing in size is asking for trouble.
There are other solutions, but it all depends on the use case. For example, in a program I have, I have a dynamically growing vector objects, where each object can contain an array. I actually dynamically allocate each element and have my vector be a vector of pointers. But that might be overkill depending on the application.