简体   繁体   English

C ++ STL向量深度擦除

[英]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. 我想要的是从2到4的任何i访问v [i]都是无效的,并且编译器抛出错误。

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 如果需要检查边界,请使用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 . 除非您编写自己的工具或解决方法,否则无法使用std::vector进行此类编译时检查。 More information and some suggestions here: https://stackoverflow.com/a/32660677/1938163 更多信息和一些建议在这里: 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. 然后,您可以制作一个自定义[]at其扔在某些索引错误运营商。 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. 我认为使用constexpr访问运算符和一些static_assert可能有可能static_assert但是我不确定确切的static_assert

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM