In the following code, I erase an element (pair of integers) from a vector, and the size after deletion is decremented. But as you can see, printing the vector by index doesn’t look normal. I expect some out-of-range errors at runtime. Isn’t that correct?
vector<pair<int, int>> v;
v.push_back(make_pair(1, 2));
v.push_back(make_pair(3, 4));
v.push_back(make_pair(5, 6));
cout << "Vector size before deletion " << v.size() << endl;
pair<int, int> p = make_pair(3, 4);
int c = 0;
for (auto x:v) {
if (x.first == 3 && x.second == 4)
v.erase(v.begin()+c);
++c;
}
cout << "Vector size after deletion " << v.size() << endl;
cout << v[0].first << " " << v[0].second << endl;
cout << v[1].first << " " << v[1].second << endl;
cout << v[2].first << " " << v[2].second << endl;
cout << v[3].first << " " << v[3].second << endl;
Output
Vector size before deletion 3
Vector size after deletion 2
1 2
5 6
5 6
0 0
>Solution :
Vector operator[] does not perform bound check and access element beyond size of vector is undefined behavior.
From vector operator[] [emphasis added]:
Returns a reference to the element at specified location pos. No bounds checking is performed.
Notes
… Accessing a nonexistent element through this operator is undefined behavior.
If you are expecting std::out_of_range exception when accessing elements beyond the size of vector, use at().