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?
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: https://stackoverflow.com/a/32660677/1938163
I do not have time right now to give examples, but the only way I can think to cleanly do this is to either make a custom class to wrap or subclass vector. You could then produce a custom []
and at
operators which throw an error on certain indexes. You could even have a deletion method which adds indeces to this list of banned ones.
Now if you need the error at compile time this is harder. I think something might be possible using a constexpr
access operator and some static_assert
s but I am not confident exactly how off hand.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.