1

I have a simple yet troublesome case of using std::vector in C++. The pop_back method slowly decreases the size of the vector at the same time that it is being iterated in the for each loop. This however goes on with no problems and the size of the vector in the end of the for each loop is 0. How come that the last elements are still able to be accessed while they are not in the vector? (calling push_back on last iteration places the new number on index 0 of the vector)

#include <vector>

int main() {
    std::vector<int> v1 = {1,2,3,4,5};
    for(int& n : v1){
        n++;
        std::cout << n << " ";
        v1.pop_back();
        if(n==6){ v1.push_back(865); }
    }
    std::cout << v1.size();
    return 0;
}

Thank you!

user3625699
  • 147
  • 1
  • 9
  • 3
    Adding and removing elements to/from the vector while you are looping through it using iterators, such as in the case of a [range-based `for` loop](https://en.cppreference.com/w/cpp/language/range-for), is **undefined behavior**, `pop_back()` and `push_back()` both invalidate the `end()` iterator. A range-based `for` loop caches the `end()` iterator before entering the loop, it does not call `end()` on each iteration. A range-based `for` loop must not modify the vector itself, but it can modify the contents of the vector. – Remy Lebeau Oct 09 '19 at 20:40
  • 2
    Using `pop_back()` does not necessarily modify the capacity of the vector. The memory is still there, but should not be accessed. This is undefined behaviour though, and doing it will cause you issues. – Chris Pearce Oct 09 '19 at 20:40
  • Maybe not quite a duplicate, but certainly closely related: https://stackoverflow.com/q/20317068/179910 – Jerry Coffin Oct 09 '19 at 20:47

0 Answers0