STL - Associative Containers
cpp
stl
containers
Commonly used associative containers are:
pair
and tuple
being similar to these, have been placed in this section
Pair
The pair
container is used to club two items together
-
Declaration:
pair<Type1, Type2> myPair;
-
The data types of these two items need not be similar. Custom types also allowed
-
Initialization:
{item1, item2}
-
Access:
.first
,.second
-
Can also use structured binding to access pair elements
-
STL provides function
make_pair(item1, item2)
to construct a pair. Helpful for custom data-types
Ordered vs Unordered associative containers
Metric | set , map | unordered_set , unordered_map |
---|---|---|
Keys | Elements are sorted by keys | No sorting of elements |
Operations | Operations take O(logN) time | Operations take O(1) avg. time |
Internals | Uses balanced BST internally | Uses Hashing internally |
Custom-type | Supports custom (sortable) data types | Hash function required for custom types |
If the hash function is poorly defined, operations in
unordered_set
&unordered_map
can takeO(N)
time in worst case due to several collisions
Also refer these posts for writing better hash functions:
- C++
unordered_map
using a custom class type as the key - Blowing up
unordered_map
, and how to stop getting hacked on it - C++ STL: Order of magnitude faster hash tables with Policy Based Data Structures
Sets
Both
set
andunordered_set
store a collection of unique keys of a specified type
CPP Reference: set
, unordered_set
Declaration: set<Type>
, unordered_set<Type>
Look-up in sets
.find(item)
- Returns iterator that points to key’s location (if it exists) or to.end()
.count(item)
- Returns1
if key exists, else returns0
.- In
set
ONLY:.upper_bound(val)
,.lower_bound(val)
Size functions in sets
.empty()
, .size()
, max_size()
Iterators in sets
.begin()
,.end()
- In
set
ONLY:.rbegin()
,.rend()
Modifiers in sets
.insert()
- Add elements into the set. If already present, the new entry is not insertedinsert(item)
- Insert an elementitem
into setinsert(start_pos, end_pos)
- Insert all elements within[start_pos,end_pos)
into setinsert({...})
i.e. Initializer list
.erase()
- Remove element(s) from the set (if exists)erase(key)
orerase(itr)
- Removes that element from the seterase(start_pos,end_pos)
- Removes elements within[start_pos,end_pos)
from the set. Better used withset
.clear()
- Empties the set.merge(another_set)
- Merge keys from the other set into current set
Examples of sets
unordered_set
demo
Maps
Both
map
&unordered_map
store a collection of pairs of key-value mappings with unique keys
C++ Reference: map
, unordered_map
Declaration: map<keyType,valueType>
, unordered_map<keyType,valueType>
We can pass our custom hash function as: unordered_map<keyType, valueType, hashFunction>
Look-up in maps
.find(k)
- Returns iterator that points to location of keyk
(if it exists) or to.end()
.count(k)
- Returns1
if keyk
exists, else returns0
.- Access value from key:
.at(k)
operator - Returns the value at keyk
if it exists, else throwsstd::out_of_range
exception[k]
operator - Returns the value at keyk
. If key doesn’t exist, it creates new key and assigns it default value.
- In
map
ONLY:.upper_bound(val)
,.lower_bound(val)
Size functions in maps
.empty()
, .size()
, max_size()
Iterators in maps
.begin()
,.end()
- In
map
ONLY:.rbegin()
,.rend()
Modifiers in maps
.insert()
- Add elements into the set. If that key already present, the entry not insertedinsert(item)
- Insert an elementitem
into setinsert(start_pos, end_pos)
- Insert all elements within[start_pos,end_pos)
into setinsert({...})
i.e. Initializer list
.erase()
- Remove one/more entries from the map (if exists)erase(key)
orerase(itr)
- Removes that entry from the maperase(start_pos,end_pos)
- Removes elements within[start_pos,end_pos)
from the set. Better used withmap
.clear()
- Empties the map.merge(another_set)
- Merge keys from the other set into current set
Examples of maps
Other ways of traversing maps
Reverse traversal: It is more suited with map
unordered_map
demo
Tuple
Used for clubbing multiple items of different types together
Also refer: make_tuple()
, tie()
,
Other associative containers
multiset
, unordered_multiset
, multimap
, unordered_multimap
These allow multiple entries of a key