Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Erase and resize a vector

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading