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

后端 未结 2 1912
时光说笑
时光说笑 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: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).

提交回复
热议问题