在 c++ 中的多个字符串数组中查找公共元素
Find common element(s) in multiple arrays of strings in c++
我有 N 个字符串数组,每个数组的大小都不同...找到它们之间的共同元素的最简单方法是什么。
示例:考虑以下三个数组:
array1 = ("String1", "String2", "String3")
array2 = ("String3", "String2", "String5")
array3 = ("String2", "String3", "String5")
预期产出:
common_elements = ("String2", "String3")
"String3"
和 "String2"
存在于所有数组中,因此它们有资格进入输出数组。另一方面,"String5"
只在array2
和array3
中,而"String1"只在Array1
中,因此它们都不符合条件。
要走的路是
-
对所有数组进行排序。
std::sort
可以使用重载operator<
按字典顺序放置元素。 -
成对应用
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));
演示
对于更多字符串向量,请递归执行。(有更有效的解决方案,您可以一次遍历所有数组,但这个解决方案是快速且标准库支持的(。
相关文章:
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 需要使用模板查找数组的第二个最小和最小值
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 查找数组中指示性较大但数组中值较小的元素
- C++ 函数,用于查找数组中四个最小最大元素的总和不起作用
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素
- 查找数组中给定数字的出现次数
- 使用 std::累加来查找数组的总和
- 代码以查找数组中的最大数字,但它仅将第一个数字显示为最大数字. 有人请告诉我为什么
- 在不进行排序的情况下查找数组中n个最小值的索引
- 当数组在C++中用作参数时,查找数组的元素数
- 查找数组中数组元素的重复出现?
- 查找数组最后 3 个数字的平均值
- 查找数组中是否存在C++元素
- 查找数组中的最小更改数以进行 k 算术级数
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 有没有办法在递归中使用指针来查找数组的最小值?
- 在编写代码以查找数组中的对数时获取分段错误