To add to the previous answers - be careful that the complexity of std::set_union is two times less than the complexity of std::merge . In practice, this means that the comparator in std::set_union can be applied to an element after it is dereferenced, and with std::merge this will never happen.
Why can this be important? Consider something like:
std::vector<Foo> lhs, rhs;
And you want to create a union of lhs and rhs :
std::set_union(std::cbegin(lhs), std::cend(lhs), std::cbegin(rhs), std::cend(rhs), std::back_inserter(union));
But now suppose that Foo not copied, or is very expensive to copy, and you do not need the originals. You might think:
std::set_union(std::make_move_iterator(std::begin(lhs)), std::make_move_iterator(std::end(lhs)), std::make_move_iterator(std::begin(rhs)), std::make_move_iterator(std::end(rhs)), std::back_inserter(union));
But this behavior is undefined, since there is the possibility of moving the moved Foo ! Therefore, the correct solution:
std::merge(std::make_move_iterator(std::begin(lhs)), std::make_move_iterator(std::end(lhs)), std::make_move_iterator(std::begin(rhs)), std::make_move_iterator(std::end(rhs)), std::back_inserter(union)); union.erase(std::unique(std::begin(union), std::end(union), std::end(union));
Which has the same complexity as std::set_union .
Daniel
source share