Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ library method for intersection of two unordered_set

Tags:

c++

stl

I have two unordered_set and want the intersection of those. 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?

Thanks

like image 910
radschapur Avatar asked Jan 08 '18 22:01

radschapur


People also ask

How do you find the intersection of two sets in C++?

C++ Algorithm set_intersection() function is used to find the intersection of two sorted ranges[first1, last1) and [first2, last2), which is formed only by the elements that are present in both sets.

How does set intersection work C++?

std::set_intersection in C++ The intersection of two sets is formed only by the elements that are present in both sets. The elements copied by the function come always from the first range, in the same order. The elements in the both the ranges shall already be ordered.

How does unordered_set know if two elements are equal?

Two unordered_sets are equal if they have the same number of elements and the elements in one container are a permutation of the elements in the other container.

Can we sort unordered_set?

A) unordered_set cannot be sorted. You'd need to copy its contents into e.g. a vector , or use an std::set with your own sorting criteria. B) qsort is a C function.


1 Answers

In fact, a loop-based solutions is the best thing you can use with std::unordered_set.

There is an algorithm called std::set_intersection which allows to find an intersection of two sorted ranges:

Constructs a sorted range beginning at d_first consisting of elements that are found in both sorted ranges [first1, last1) and [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.

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.

like image 190
Edgar Rokjān Avatar answered Sep 21 '22 05:09

Edgar Rokjān