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

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

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

例如,这里有两个向量:

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

而我想要的是如果元素是"one",则根据条件删除。最后的结果是:

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;

当您搜索给定文本的矢量时,您可以删除一个包含文本和值的元素。

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