-6
vector<int> v = { 1,2,3,4,5 };
for (auto beg = v.begin(); beg != v.end();++beg)
{
    if (beg == v.begin())
        v.push_back(50);
}

During run time, it says : "vector iterator not incrementable".

gigi
  • 669
  • 6
  • 11

2 Answers2

9

See std::vector::push_back.

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

In your example, beg is an iterator. It is being invalidated by the push_back, you cannot use it anymore.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
1

As mentioned std::vector::push_back() may invalidate your iterator. Possible, but pretty ugly solution could be:

for (auto beg = v.begin(); beg != v.end();++beg)
{
    if (beg == v.begin()) {
        v.push_back(50);
        beg = v.begin();
    }
}

but your logic seems convoluted, why not push back just before the loop?

Slava
  • 43,454
  • 1
  • 47
  • 90
  • I didn't thought about the code, I just wanted to know why this is an error. – gigi Jan 09 '17 at 20:33
  • Answers on SO are not only for you, and that is the reason I asked you to fix your code. – Slava Jan 09 '17 at 20:35
  • I think that the reason why push_back() invalidates all iterators is because push_back() change the memory address occupied by the vector, am I right? – gigi Jan 09 '17 at 20:39
  • @gigi `push_back` **may** invalidate iterators. And actually in your updated example most probably it would not to. Now you should see why [mcve] is asked. But yes, vector may have to reallocate memory for storage if `capacity()` will be not big enough to hold new data size. – Slava Jan 09 '17 at 20:42