0

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;
}
  • Note that after all the calls to push back, the vector contains `[0,0,0,0,0,1,2,3,4]`. Your constructor creates a vector with a *size* of 5. I suspect you were trying to create an empty vector with *capacity* of 5 (in which case, your code would work). To do that: `vector a; a.reserve(5);` – Martin Bonner supports Monica Dec 23 '17 at 16:32
  • This answer is what I think exactly.I did not know that constructor can not reserve memories. – parkgibyeong Dec 24 '17 at 06:22

1 Answers1

3

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

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23