Range-based for loop and std::vector.push_back() crashing the program

后端 未结 2 1902
时光说笑
时光说笑 2020-12-10 09:25
#include 
#include 

int main() {
    std::vector vec;
    for (int i = 0; i < 42; ++i) {
        vec.push_back(i);
              


        
相关标签:
2条回答
  • 2020-12-10 10:09

    Once you call std::vector::push_back or most non-const function for that matter the iterators are invalidated (When the new size exceeds the current capacity of the vector which causes the memory to be re-allocated internally)

    You can find some good references on how standard containers or iterators work in general. I hope that gets you started!

    0 讨论(0)
  • 2020-12-10 10:27

    From 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.

    Range-based for loop uses iterators internally. Using push_back may cause these iterators to be invalidated.

    Edit : Notice that when y == 22 you are inserting a 65th element into your vector. It's likely the capacity was 64. Many implementations increase capacity by powers of 2 (doubling it each time).

    0 讨论(0)
提交回复
热议问题