2

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;
}
  • Possible duplicate: https://stackoverflow.com/questions/8628951/remove-elements-of-a-vector-inside-the-loop – Rakete1111 Jul 04 '17 at 17:17
  • 2
    Did you attempt to read the documentation of [std::vector::erase](http://en.cppreference.com/w/cpp/container/vector/erase)? _Invalidates iterators and references at or after the point of the erase, including the end() iterator._ – Algirdas Preidžius Jul 04 '17 at 17:17
  • 2
    In other words if you want to erase from a vector using a loop you need to iterate backwards to avoid invalidating the iterator. – jodag Jul 04 '17 at 17:20
  • Okey i don't know about that :/ thanks for help, i'm a little new in c++ –  Jul 04 '17 at 17:20

2 Answers2

4

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);
21koizyd
  • 1,843
  • 12
  • 25
2

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.

jodag
  • 19,885
  • 5
  • 47
  • 66