std::map is an associative container that stores elements in key-value pairs. Each key in a std::map is unique, and each key is associated with exactly one value. This container provides fast retrieval of values based on their keys.
Introduction to std::map
C++ is a powerful programming language known for its versatility and efficiency. One of its most valuable components is the Standard Template Library (STL), which includes std::map, a dynamic associative container. This container allows for the storage and quick retrieval of key-value pairs, making it an essential tool for many programming tasks.
What is std::map?
std::map is an associative container that stores elements in key-value pairs. Each key in a std::map is unique, and each key is associated with exactly one value. This container provides fast retrieval of values based on their keys.
Key Features of std::map
Associative Container: Stores elements in key-value pairs.
Unique Keys: Each key in the map is unique.
Automatic Sorting: Keys are automatically sorted.
Efficient Lookup: Fast retrieval of values based on keys.
Balanced Binary Tree: Typically implemented as a balanced binary tree (e.g., red-black tree).
How to Declare and Initialize a std::map
Here are some basic ways to declare and initialize a map:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> map1; // Empty map with integer keys and string values
std::map<int, std::string> map2 = {{1, "one"}, {2, "two"}, {3, "three"}}; // Map initialized with key-value pairs
return 0;
}
Basic Operations on std::map
Adding Elements
Elements can be added to the map using the insert method or the [] operator:
Elements in a map can be accessed using the [] operator or the at method:
std::string value = map2[1]; // Access value associated with key 1
std::string value2 = map2.at(2); // Access value associated with key 2 (with bounds checking)
Removing Elements
Elements can be removed from the map using the erase method:
map1.erase(4); // Removes element with key 4
Iterating Over Elements
You can use a range-based for loop or an iterator to iterate over the elements of a map: