简体   繁体   English

C ++库方法用于两个unordered_set的交集

[英]C++ library method for intersection of two unordered_set

I have two unordered_set and want the intersection of those. 我有两个unordered_set并想要它们的交集。 I can't find a library function to do that. 我找不到一个库函数来做到这一点。

Essentially, what I want is this: 基本上,我想要的是这样的:

unordered_set<int> a = {1, 2, 3};
unordered_set<int> b = {2, 4, 1};

unordered_set<int> c = a.intersect(b); // Should be {1, 2}

I can do something like 我可以做点什么

unordered_set<int> c;
for (int element : a) {
  if (b.count(element) > 0) {
    c.insert(element);
  }
}

but I think there should be a more convenient way to do that? 但我认为应该有更方便的方法吗? If there's not, can someone explain why? 如果没有,有人可以解释原因吗? I know there is set_intersection, but that seems to operate on vectors only? 我知道有set_intersection,但这似乎仅适用于矢量?

Thanks 谢谢

In fact, a loop-based solutions is the best thing you can use with std::unordered_set . 事实上,基于循环的解决方案是您可以使用std::unordered_set的最佳选择。

There is an algorithm called std::set_intersection which allows to find an intersection of two sorted ranges: 有一个名为std::set_intersection的算法,它允许查找两个有序范围的交集:

Constructs a sorted range beginning at d_first consisting of elements that are found in both sorted ranges [first1, last1) and [first2, last2). 构造一个从d_first开始的排序范围,该排序范围由在排序范围 [first1,last1]和[first2,last2)中找到的元素组成。

As you deal with std::unordered_set , you cannot apply this algorithm because there is no guaranteed order for the elements in std::unordered_set . 在处理std::unordered_set ,您无法应用此算法,因为std::unordered_set的元素没有保证顺序。

My advice is to stick with loops as it explicitly says what you want to achieve and has a linear complexity ( O(N) , where N is a number of elements in the unordered set you traverse with a for loop ) which is the best compexity you might achieve. 我的建议是坚持使用循环,因为它明确地说明了你想要实现的东西,并且具有线性复杂度( O(N) ,其中N是你用for循环遍历的无序集合中的元素数量),这是最好的复杂性你可能会实现。

There is a function from std called set_intersection . std有一个名为set_intersection的函数。 However, it would have a very high complexity using it with std::set as input parameter.. A better solution is, create two vectors from those sets and use set_intersection with vectors as input parameters. 但是,使用std::set作为输入参数会有很高的复杂性。更好的解决方案是,从这些集合中创建两个向量,并使用带向量的set_intersection作为输入参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM