std::unordered_set<Key> · C++
insert(first, last): union
Inserts every element of a range: the way to compute a union in place.
template<class InputIt> void insert(InputIt first, InputIt last);
Complexity
| Average | O(m) for m inserted elements |
|---|---|
| Worst case | O(m · n) |
| Extra space | O(m) |
One average-O(1) insert per element. An intersection is a loop over the smaller set with contains on the larger one: O(min(n, m)) on average.
Tested example
std::unordered_set<int> a{1, 2, 3};
const std::vector<int> b{3, 4};
a.insert(b.begin(), b.end()); // union, in place
assert(a.size() == 4);
std::unordered_set<int> common; // intersection: no member function, loop over the smaller set
for (int x : std::unordered_set<int>{2, 4, 6})
if (a.contains(x)) common.insert(x);
assert((common == std::unordered_set<int>{2, 4}));
Parameters
- first, last
- Any input range.
Behaviour
- Returns
- Nothing.
- Errors and preconditions
- As insert.
- Changes
- Adds the new elements.
- Memory and invalidation
- May rehash.