Reputation:
Why programm stopped? That programm compile, but if i run, that he break, and give some message about iterator vector not incrementable. What is wrong?
int main()
{
std::vector<int> vec;
for (int i = 1; i <= 100; ++i)
vec.push_back(i);
for (auto itr = vec.begin() + 5; itr < vec.end() - 5; ++itr)
vec.erase(itr);
for (const auto& itr : vec)
std::cout << itr << std::endl;
return 0;
}
Upvotes: 2
Views: 392
Reputation: 22184
If you want to erase elements in the vector using a for loop you can do so by iterating backwards through the set of elements. For example
#include <vector>
#include <iostream>
int main()
{
std::vector<int> vec;
for (int i = 0; i <= 100; ++i)
vec.push_back(i);
for (auto itr = vec.end() - 6; itr > vec.begin() + 4; --itr)
vec.erase(itr);
for (const auto& itr : vec)
std::cout << itr << std::endl;
return 0;
}
As pointed out by 21koizyd, if you want to erase a range of elements you can use the second argument of std::vector::erase
to specify an end element.
Upvotes: 2
Reputation: 1993
You are wrong, because function erase don't anull iterators. So you can do like that:
auto itr = vec.begin() + 5;
while (itr != vec.end() - 5) {
itr = vec.erase(itr);
}
or more flexible ( without loop )
vec.erase(vec.begin() + 5, vec.end() - 5);
Upvotes: 4