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;
}
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);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.