如何找到两个集合的交集
How do I find the intersection of 2 sets?
从两个集合中创建包含两个集合的值的子集的最有效方法是什么?任何c++ STL库都可以用来解决这个问题(如果可能的话,不需要Boost库):
Set A = {2, 3, 5, 7, 11, ...}
Set B = {1, 3, 5, 7, 9, 11, ...}
Subset should be = {3, 5, 7, 11, ...}
您可以通过使用set_intersection
来做到这一点,您将在那里找到如何使用它的示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v1{2, 3, 5, 7, 11};;
std::vector<int> v2{1, 3, 5, 7, 9, 11};
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<int> v_intersection;
std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(v_intersection));
for(int n : v_intersection)
std::cout << n << ' ';
}
结果将是:
3 5 7 11
按照下面的描述使用std::set_intersection
:
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- STL:在没有输出的情况下处理两个集合
- 如何获得两个 std::unordered_map 的集合交集?
- 是同一集合上的两个不同的迭代器
- 使用 STL 算法查找集合中的前两个不相邻元素
- C++ 创建指向两个相关矢量集合中的对象的指针集合
- 将元素存储在具有两个可能索引的集合中
- 比较两个无序集合的相等性有多昂贵
- 在C++中,如何最好地解耦两个必须维护彼此引用集合的类
- 查找两个集合之间的邻近匹配对
- 如何在c++中计算两个STL集合的交集的大小
- 一个集合是否可能包含指向同一对象的两个共享指针?
- 如何找到两个集合的交集
- 在c++中,两个线程/对象在一个对象集合中可以安全地做什么?