【问题标题】:How do I find the intersection of 2 sets? [duplicate]如何找到 2 个集合的交集? [复制]
【发布时间】:2015-08-16 11:30:37
【问题描述】:

从包含两个集合的值的 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, ...}

【问题讨论】:

  • 你看过std::set了吗?
  • @bigOTHER 的答案是正确的,但这个问题是“howto”问题还是算法问题? (如果是算法,并且集合是有序的,那么stackoverflow.com/questions/5958169/…)。

标签: c++ algorithm stl set set-intersection


【解决方案1】:

您可以使用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

【讨论】:

  • 至少链接更好reference
  • @LogicStuff 已更新,谢谢
  • @bigOTHER 我的意思主要是因为示例更清晰。
  • 输出中缺少 11,因为在硬编码值(例如 5)而不是使用 std::beginstd::end 时会出现一个典型的错误。
  • @LogicStuff 我更新了示例
【解决方案2】:

使用std::set_intersection,如下所述:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 2015-09-24
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
相关资源
最近更新 更多