根据第一个向量的元素从两个 std::vector 中删除元素

Remove elements from two std::vectors based on the first vector's elements

本文关键字:元素 两个 std 删除 vector 第一个 向量      更新时间:2023-10-16

我必须用相同数量的元素向量。我想根据一个条件删除第一个向量的元素,但我也想从第二个向量中删除位于相同位置的元素。

例如,这里有两个向量:

std::vector<std::string> first = {"one", "two", "one", "three"}
std::vector<double> second = {15.18, 14.2, 2.3, 153.3}

我想要的是删除基于条件,如果元素是"1"。最后的结果是:

std::vector<std::string> first = {"two", "three"}
std::vector<double> second = {14.2, 153.3}

我可以从first中删除元素,使用:

bool pred(std::string name) {
  return name == "one";
}
void main() {
  std::vector<std::string> first = {"one", "two", "one", "three"}
  first.erase(first.begin(), first.end(), pred);
}

但是我不知道从第二个向量中删除元素的方法。

我建议您更改数据结构。使用一个结构体来保存两个元素:

struct Entry
{
  std::string text;
  double      value;
};

现在它变成了一个包含两个元素的向量:
std::vector<Entry> first_and_second;

在vector中搜索给定文本时,可以删除一个同时包含文本和值的元素。

for(int i = first.size() - 1; i >= 0; i--){
   if(first[i] == "one"){
       first.erase(first.begin() + i);
       second.erase(second.begin() + i);
   }
}
相关文章: