Skip to content Skip to sidebar Skip to footer

C++: Push_back In Std::vector While Iterating It

Following code snippet provides a very weird output. I was expecting an overflow( Python gives a MemoryError) #include #include int main() { s

Solution 1:

In C++ adding elements to a vector may cause reallocation of the contained data, which will invalidate all iterators. That means you can't loop over the vector using iterators (which is what the range-based for loop does) while also inserting new elements.

You can however iterate using indexes and use the vector size as condition, since indexes will always be the same.

Solution 2:

If the vector is resized, the iterator will become invalid.

You could do it if you reserve in advance.

Keep in mind that for range will operate on the iterator bounds defined before any changes are made. So will only get a copy of your list appended.

#include<iostream>#include<vector>intmain(){
    std::vector<int> a{1,2,3};

    a.reserve(10);           // 10 should be enough to get a copy without reallocatingfor( autoconst & item : a)
        a.push_back(item);

    for( autoconst & item : a)
        std::cout<<item<<',';

    return0;
}

Output:

1,2,3,1,2,3,

I would not recommend an approach like this because I don't consider it clean or clear. However, if you refer to the standard, this behaviour is expected:

23.3.6.5 vector modifiers

With respect to the use of insert,emplace,emplace_back, push_back.

Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid.

That is, if no reallocation happens, you can trust your iterators before the insertion point. So as long as the capacity of your vector is high enough, you can append with no problems.

Post a Comment for "C++: Push_back In Std::vector While Iterating It"