C++20 sections · 1024 units
Open in Course

Inserting into Sets

How to add

Use s.insert(value) to add an element. If the element already exists, nothing happens and the set stays unchanged. Sets never contain duplicate values. Insert returns a pair: auto [it, success] = s.insert(5); gives you an iterator to the element and a bool indicating whether a new element was added to the set.

You can insert ranges from other containers: s.insert(v.begin(), v.end()) adds all unique elements from vector v. This runs in O(mlogn)O(m \log n) for m elements being inserted.