简体   繁体   中英

Merging two std::set's and (not yet) std::set::merge()

I just wrote this code:

// Somewhere earlier, the equivalent of this happens.
std::set<T> a;
std::set<T> b;
FillMeUp(a);
FillMeUp(b);

// Later, in another function that sees a and b, this happens.
std::set<T> c;
std::set_union(a.begin(), a.end(),
               b.begin(), b.end(),
               std::inserter(c, c.begin()));
a.swap(c);

The point is that the second bit of code, under certain circumstances, wants to merge a and b together into a .

(For motivation: I have an array of objects with sets. I iterate over that array. If a certain condition is met, the object I am looking at essentially duplicates the object I saw just before, so I'd like to merge its set into the set just before.)

There's a new function in C++17 called std::set::merge , but my g++ 5.3.1 apparently doesn't know about it (says g++ 5.3.1 invoked with -std=c++17).

The question, really, is could I do better than what I've done?

Officially, std::set::merge is defined in the draft standard :

Attempts to extract each element in a2 and insert it into a using the comparison object of a. In containers with unique keys, if there is an element in a with key equivalent to the key of an element from a2, then that element is not extracted from a2.

With a complexity of:

N log(a.size()+ N) where N has the value a2.size().

Since this matches the complexity of one of the overloads of insert :

template< class InputIt >
void insert( InputIt first, InputIt last );

It sounds like a glorified wrapper of insert :

a.insert(b.begin(), b.end());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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