在 c++ 中的多个字符串数组中查找公共元素

Find common element(s) in multiple arrays of strings in c++

本文关键字:查找 数组 元素 c++ 字符串      更新时间:2023-10-16

我有 N 个字符串数组,每个数组的大小都不同...找到它们之间的共同元素的最简单方法是什么。

示例:考虑以下三个数组:

array1 = ("String1", "String2", "String3")
array2 = ("String3", "String2", "String5")
array3 = ("String2", "String3", "String5")

预期产出:

common_elements = ("String2", "String3")

"String3""String2"存在于所有数组中,因此它们有资格进入输出数组。另一方面,"String5"只在array2array3中,而"String1"只在Array1中,因此它们都不符合条件。

要走的路是

  1. 对所有数组进行排序。std::sort可以使用重载operator<按字典顺序放置元素。

  2. 成对应用 std::set_intersection .

示例代码:

std::vector<std::string> v1 {"hello","world"};
std::vector<std::string> v2 {"goodbye","world"};
std::sort(std::begin(v1), std::end(v1));
std::sort(std::begin(v2), std::end(v2));
std::vector<std::string> common_elements;
std::set_intersection(std::begin(v1), std::end(v1)
                    , std::begin(v2), std::end(v2)
                    , std::back_inserter(common_elements));

演示

对于更多字符串向量,请递归执行。(有更有效的解决方案,您可以一次遍历所有数组,但这个解决方案是快速且标准库支持的(。