如何深度擦除矢量?C++ STL矢量深度擦除
请考虑以下代码。
#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;
}
输出是
1 having index 0
2 having index 1
3 having index 2
4 having index 3
5 having index 4
2
4
欲正在访问v实现任意i为2至4是无效的和编译器以引发错误[I]什么。
用简单的话来说,如何深度擦除矢量?
它是UB;你应该自己检查一下。或者使用'std :: vector :: at'。 – songyuanyao
一个向量通过定义将其元素存储在连续内存中,所以你想要的不是可能的 – user463035818
而且你甚至希望它成为编译时错误。 – LogicStuff