比较两个向量 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5225820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:43:38  来源:igfitidea点击:

Compare two vectors C++

c++stl

提问by Adrian

I was wondering is there any function to compare 2 string vectors to return the number of different(or the same) elements? Or i have to iterate over both of them and test item by item.
Thanks.

我想知道是否有任何函数可以比较 2 个字符串向量以返回不同(或相同)元素的数量?或者我必须遍历它们并逐项测试。
谢谢。

回答by Erik

std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<string> v3;
std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));

Or, if you don't want to sort:

或者,如果您不想排序:

std::set<string> s1(v1.begin(), v1.end());
std::set<string> s2(v2.begin(), v2.end());
std::vector<string> v3;
std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(v3));

You may want to use a multiset if there could be duplicates in a vector.

如果向量中可能存在重复项,您可能需要使用多重集。

回答by JaredPar

I don't know of an existing function but writing one yourself shouldn't be too much trouble.

我不知道现有的函数,但自己编写一个函数应该不会太麻烦。

int compare(const vector<string>& left, const vector<string>& right) {
  auto leftIt = left.begin();
  auto rightIt = right.begin();
  auto diff = 0;
  while (leftIt != left.end() && rightIt != right.end()) {
    if (*leftIt != *rightIt) {
      diff++;
    }
    leftIt++;
    rightIt++;
  }

  // Account for different length vector instances
  if (0 == diff && (leftIt != left.end() || rightIt != right.end())) {
    diff = 1;
  }

  return diff;
}

Notes

笔记

  • Omitted std::prefix for brevity
  • This function needs to be updated if it should handle vector<string>instances of different lengths
  • std::为简洁起见省略前缀
  • 如果它应该处理vector<string>不同长度的实例,则需要更新此函数

回答by Morten Kristensen

Have a look at set_difference()and set_intersection(). In both cases you need to have your containers sorted beforehand.

看看set_difference()set_intersection()。在这两种情况下,您都需要事先对容器进行分类。