Search code examples
c++vectorsetintersectionunordered-set

C++ Inconsistent result by set_intersection method on unordered_set and set


I was working on a problem on Leetcode when I encountered this inconsistency with unordered_set and set. Let two vectors be nums1 = [4,9,5] and nums2 = [9,4,9,8,4]. We have to find their intersection so I did the following two things:

1.

unordered_set<int> s1 (nums1.begin(), nums1.end());
unordered_set<int> s2 (nums2.begin(), nums2.end());
vector <int> s;
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), back_inserter(s));

2. Replaced unordered_set with set

set<int> s1 (nums1.begin(), nums1.end());
set<int> s2 (nums2.begin(), nums2.end());
vector <int> s;
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), back_inserter(s));

Result from approach 1. is [9] while from approach 2. is [9,4] (which is correct). Am I missing some key concepts of C++ STL?


Solution

  • In first snipped only first intersecting range is returned, because original set is unsorted

    Constructs a sorted range beginning at d_first consisting of elements that are found in both sorted ranges [first1, last1) and [first2, last2). If some element is found m times in [first1, last1) and n times in [first2, last2), the first std::min(m, n) elements will be copied from the first range to the destination range.

    First sorted range is {4,9} and second sorted range is {9}. Intersection of those two is indeed {9}.

    For set {4,9} and {9,4} are equal and sets are sorted ranges. So both results are correct for given ranges.