Q:

C++ find() function does not work after adding items

I want to know why "a.push_back(4)" makes runtime error.
without "a.push_back(4)" makes no runtime error.
#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;
}

A:

The push_back(4) invalidates your iterators. That is why this code produces an error.

