Maps are associative containers that store key–value pairs in sorted order using a self-balancing Red-Black Tree. They provide efficient O(log n) time complexity for insertion, deletion, and searching operations.
- Maps do not allow duplicate keys.
- They support ordered traversal and functions like upper_bound() and lower_bound().
Output1 Geeks
2 For
3 Geeks
Explanation: Above program demonstrates how to create and initialize a map in C++ using key–value pairs. It then iterates through the map using a range-based loop and prints each key along with its corresponding value.
Syntax
The map container is defined as std::map class templateinside the <map> header file.
map<key_type, value_type> m;
where,
- key_type: Data type of key.
- value_type: Data type of value.
- m: Name assigned to map.
Basic Operations
Basic operations on map containers are shown below:
1. Inserting Elements
- The insert() operation adds a new key-value pair to the map only if the key is not already present.
- If the key exists, insert() does not update the value and leaves the map unchanged.
- Time complexity to insert is O(log n).
Output1 Geeks
2 For
3 Geeks
2. Accessing Elements
- We can access elements with [] operator which returns the value for a given key and inserts the key with a default value if it doesn't exist.
- To check if a key exists without adding it by we can use find().
- Time complexity to access elements by key is O(log n).
3. Updating Elements
- To update a value, we can simply assign a new value to an existing key using map[key]= newValue; If the key already exists , the value gets updated.
- Time complexity to update element by key O(log n).
4. Finding Elements
- find() function is used to check if key exists in a map which looks for key and returns its position if found.
- If key is not present in the map, find() returns a special value called end(), meaning not found.
- Time complexity to find element by key is O(log n).
5. Traversing
- Loops can be used to traverse all key-value pairs in a map, which visits each pair in order sorted by the keys.
- Time complexity to traverse in a map is O(n).
Output1 Geeks
2 For
3 Geeks
6. Deleting Elements
- To delete a key and its value from map use erase(key), which deletes the pair if the key exists, else does nothing.
- Time complexity to delete an element by key O(log n).