如何找到两组的交集?

Str*_*ker 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, ...}
Run Code Online (Sandbox Code Playgroud)

Big*_*her 5

您可以通过使用来做到这一点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 << ' ';
}
Run Code Online (Sandbox Code Playgroud)

结果将是:

 3 5 7 11
Run Code Online (Sandbox Code Playgroud)

  • 输出中缺少 11 是因为当硬编码 5 这样的值而不是使用 `std::begin` 和 `std::end` 时会出现一个典型的错误。 (2认同)