kalpa kalpa - 22 days ago 9
C++ Question

C++ STL vector Deep erase

How to deep erase a vector?

Consider the following code.

#include<algorithm>
#include<iostream>
#include<iterator>
#include<vector>

using namespace std;

int main(){
vector<int> v {1,2,3,4,5};
for_each(begin(v),end(v),[&v](int& n){
static auto i = (int)0;
if(n == 2){
v.erase ( begin(v) +2, end(v));
}
cout << n << " having index " << i++ << endl;
});
v.erase ( begin(v) +2, end(v));
cout << v.size() << endl << v[4] << endl;
}


Output is

1 having index 0
2 having index 1
3 having index 2
4 having index 3
5 having index 4
2
4


What I want is accessing v[i] for any i from 2 to 4 to be invalid and compiler to throw an error.

In simpler words how to deep erase a vector?

Answer

You're triggering undefined behavior and therefore your results cannot be trusted.

If you need to check for boundaries use std::vector::at

vector<int> v{ 1,2,3,4,5 };
v.erase(begin(v) + 2, end(v));
try {
  auto val = v.at(4);
} catch (std::out_of_range&) {
  cout << "out of range";
}

Unless you code your own facility or workaround, you can't have such compile-time checks with std::vector. More information and some suggestions here: http://stackoverflow.com/a/32660677/1938163