STL set_union and set_intersection on unsorted vectors

前端 未结 3 1453
醉梦人生
醉梦人生 2021-01-27 02:16

Below is my code on set intersection and union test that I did. I don\'t understand why it the output is incorrect when I commented out the sort function. Why is the sort necess

相关标签:
3条回答
  • 2021-01-27 02:46

    In case you care about the official wording from the standard (§25.4.5/1):

    This section defines all the basic set operations on sorted structures. They also work with multisets (23.4.7) containing multiple copies of equivalent elements. The semantics of the set operations are generalized to multisets in a standard way by defining set_union() to contain the maximum number of occurrences of every element, set_intersection() to contain the minimum, and so on. [emphasis added]

    That section includes the specifications for std::includes, std::set_union, std::set_intersection, std::set_difference, and std::set_symmetric_difference, so the requirement for sorted inputs applies to all of these algorithms.

    0 讨论(0)
  • 2021-01-27 02:50

    That's required. This is excerpt from documentation of std::union.:-

    Constructs a sorted range beginning at d_first consisting of all elements present in one or both sorted ranges [first1, last1) and [first2, last2).
    1) Expects both input ranges to be sorted with operator<
    2) Expects them to be sorted with the given comparison function comp
    If some element is found m times in [first1, last1) and n times in [first2, last2), then all m elements will be copied from [first1, last1) to d_first, preserving order, and then exactly std::max(n-m, 0) elements will be copied from [first2, last2) to d_first, also preserving order.
    
    0 讨论(0)
  • 2021-01-27 03:02

    Because it is a requirement for std::set_union:

    Constructs a sorted range beginning at d_first consisting of all elements present in one or both sorted ranges [first1, last1) and [first2, last2).

    1) Expects both input ranges to be sorted with operator<

    2) Expects them to be sorted with the given comparison function comp

    (emphasis mine)

    you shouldn't call these algorithms on unsorted ranges.

    0 讨论(0)
提交回复
热议问题