This question already has answers here:

Iterator invalidation rules
(5个答案)
我想知道为什么“a.push_back(4)”会导致运行时错误。
如果没有“a.push_back(4)”,则不会产生运行时错误。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void main()
{
    vector<int> a(5);
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    vector<int>::iterator begIt = begin(a);
    vector<int>::iterator endIt = end(a);

    a.push_back(4); // Once it is removed, this program will work well.

    auto begIt2 = begin(a);
    auto endIt2 = end(a);

    auto findIt = find(begIt, endIt, 4);
    if (findIt == endIt)
        cout << "not found";
    else
        cout << *findIt;
}

最佳答案

push_back(4)使迭代器失效。这就是为什么这段代码会产生错误。

10-01 01:41