gpt4 book ai didi

c++ - 在 C++ 中删除 vector 中的范围元素

转载 作者:行者123 更新时间:2023-11-28 03:06:56 25 4
gpt4 key购买 nike

我正在尝试删除 vector 中的一些元素,这些元素由另一个索引 vector 指定。我遇到段错误。我遇到段错误的原因是我的 vector 的大小随着元素的删除而减小,所以看起来我试图超过索引。谁能帮忙?提前致谢

#include <iostream>
#include <vector>
using namespace std;

int main()
{
int a = 5, b = 10 , c = 20, d = 30, e = 40 , f = 50;
vector<int> vec;

vec.push_back(a);
vec.push_back(b);
vec.push_back(c);
vec.push_back(d);
vec.push_back(e);
vec.push_back(f);

vector<int> index_2_b_el;

index_2_b_el.push_back(1); //delete b
index_2_b_el.push_back(3); //delete d
index_2_b_el.push_back(4); //delete e

for(int i=0; i<index_2_b_el.size(); i++)
{
vec.erase(vec.begin() + index_2_b_el[i]);
// "b", "d" and "e" should be deleted
}

for(int i=0; i<vec.size(); i++)
{
cout<< "vec: "<< vec[i]<<endl;
// "a", "c" and "f" should remain
}

return 0;
}

最佳答案

正如您所说的 vector 大小发生变化,还要注意索引也会发生变化,因此您不会删除您认为的元素。我可以建议对索引 vector (std::sort) 进行排序,然后从最大的索引向下移除。这样,以前的索引不会因删除之前的索引而失效。

关于c++ - 在 C++ 中删除 vector 中的范围元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19446864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com