Sets are containers that store unique elements. There are four kinds of sets in C++
- set
- multiset
- unordered_set
- unordered_multiset
set
- Internally, keys are sorted following a strict weak ordering criteria - default is
less<Key>
- Implemented using binary search trees, so access takes O(log n)
1 2 3 4
| template < class T, // set::key_type/value_type class Compare = less<T>, class Alloc = allocator<T> > class set;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #include <set>
set<int> s;
s.insert(1); s.insert(2); s.insert(3); auto res = s.insert(3); if (res.second) cout << "value = " << *res.first << " was newly added!" << "\n";
if (s.find(11) == s.end()) cout << "11 is not present in the set" << "\n";
auto it = s.find(2); cout << *it << "\n";
s.erase(3); s.erase(it);
for (auto ele: s) cout << ele << "\n";
|
multiset
Like set, but multiple values could have an equivalent key.
1 2 3 4
| template < class T, // multiset::key_type/value_type class Compare = less<T>, class Alloc = allocator<T> > class multiset;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <set>
multiset<int> s;
s.insert(1); s.insert(2); s.insert(3); s.insert(3); s.insert(4);
if (s.find(11) == s.end()) cout << "11 is not present in the set" << "\n";
auto it = s.find(2); cout << *it << "\n";
s.erase(4); s.erase(it);
cout << "no. of elements with key 3 = " << s.count(3) << "\n";
for (auto ele: s) cout << ele << "\n";
auto range_it = s.equal_range(3);
for (auto it = range_it.first; it != range_it.second; ++it) cout << *it << "\n";
|
unordered_set
- Internally, keys are not sorted and a hash value of key is used to organise the values in buckets.
- Faster access time due to hash function -> constant average time
1 2 3 4 5
| template < class Key, // unordered_set::key_type/value_type class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator<Key> > class unordered_set;
|
1 2 3 4 5 6 7
| #include <unordered_set>
unordered_set<int> s;
|
unordered_multiset
- Like
unordered_set
, but multiple values could have an equivalent key.
- Faster compared to
multiset
, as it uses hash function to internally store values in buckets based on the key.
1 2 3 4 5
| template < class Key, // unordered_multiset::key_type/value_type class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator<Key> > class unordered_multiset;
|
1 2 3 4 5 6 7
| #include <unordered_set>
unordered_multiset<int> s;
|
References