如何找到两个集合的交集

How do I find the intersection of 2 sets?

本文关键字:集合 两个 何找      更新时间:2023-10-16

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

http://www.cplusplus.com/reference/algorithm/set_intersection/