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".
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".
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.
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?