c++ - 如何找到 2 组的交集?

标签 c++ algorithm stl set set-intersection

<分区>

从 2 个集合中创建包含两个集合值的子集的最有效方法是什么?任何 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

关于c++ - 如何找到 2 组的交集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32034577/

相关文章:

c++ - 维护一个 std::set<boost::shared_ptr>

算法 - GCD 和 LCM 问题

algorithm - 是否有一种路径算法不是寻找从 A 点到 B 点的路径,而是返回覆盖整个 map 的路径?

c# - 实现一个有效的算法来找到两个字符串的交集

c++ - 将 vector 作为参数传递并使用它,为什么会崩溃?

C++ double 据类型

c++ - 函数中无法识别类的成员函数

c++ - Cocos2d-x自定义内存模型有哪些优势?

c++ - std::vector.pop_back() 会改变 vector 的容量吗?

c++ - 实现自定义的类 STL 数据结构