C++ Maps
A map in C++ is an associative container that stores elements in key-value pairs. Each key is unique, and it is used to access the corresponding value. Maps are part of the Standard Template Library (STL) and provide efficient retrieval of values based on their keys.
Key Topics
Overview of Maps
Maps offer several advantages:
- Fast retrieval of values using keys.
- Keys are automatically sorted.
- Efficient insertion and deletion of elements.
Declaring Maps
To declare a map, include the map
header and use the following syntax:
#include
Common Map Operations
Here are some common operations you can perform on maps:
insert()
: Adds a key-value pair to the map.erase()
: Removes a key-value pair from the map based on the key.find()
: Searches for a key in the map and returns an iterator to it.operator[]
: Accesses the value associated with a key (inserts a new key with a default value if it doesn't exist).count()
: Returns the number of occurrences of a key (either 0 or 1 for maps).size()
: Returns the number of key-value pairs in the map.
Example: Basic Map Operations
#include
#include
Output:
Size of map: 2
Alice's age: 30
Size of map after erasing Bob: 1
Iterating Over Maps
Maps can be iterated using iterators or range-based for loops. The elements will be accessed in sorted order based on the keys.
Example: Iterating Over a Map
#include
#include
Output:
Map elements:
Alice is 30 years old.
Bob is 25 years old.
Charlie is 35 years old.
Exercises with Maps
Here are some exercises to practice your understanding of maps:
- Implement a program to count the frequency of words in a given text.
- Create a phone book application that allows users to add, search, and remove contacts.
- Write a function that merges two maps into one, summing values for duplicate keys.
Key Takeaways
- Maps are associative containers that store unique keys paired with values.
- Common operations include inserting, erasing, and accessing values using keys.
- Maps provide efficient access and manipulation of key-value pairs.
- Iterating over maps can be done using iterators or range-based for loops.