C++ Container Classes<map>
In C++,<map>It is part of the Standard Template Library (STL), providing an associative container for storing key-value pairs.
mapThe elements in the container are automatically sorted by the order of keys, making it very suitable for scenarios that require fast lookup and ordered data.
Definition and characteristics
- Key-value pairs:
mapIt stores key-value pairs, where each key is unique. - Sorting:
mapThe elements in it are automatically sorted by the order of keys, usually in ascending order. - Uniqueness: each key in
mapcan only appear once. - Bidirectional iterator:
mapIt provides bidirectional iterators, allowing elements to be traversed forward and backward.
Basic Syntax
Include header file:
#include <map>
Declare the map container:
std::map<key_type, value_type> myMap;
key_typeis the type of the key.value_typeis the type of the value.
Insert elements:
myMap[key] = value;
Access elements:
value = myMap[key];
Traverse map:
for (std::map<key_type, value_type>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << " => " << it->second << std::endl;
}
In C++11 and later standards, the traversal part can be simplified to a range-based for loop, making the code more concise:
for (auto &p : m) {
std::cout << p.first << " : " << p.second << std::endl;
}
Example
The following is an example usingmapa simple example, we will create amapto store employee names and their ages, and traverse thismapto print each employee's name and age.
Example
#include <string>
int main() {
// Create a map container to store employee names and ages
std::map<std::string, int> employees;
// Insert employee information
employees["Alice"] = 30;
employees["Bob"] = 25;
employees["Charlie"] = 35;
// Traverse the map and print employee information
for (std::map<std::string, int>::iterator it = employees.begin(); it != employees.end(); ++it) {
std::cout << it->first << " is " << it->second << " years old." << std::endl;
}
return 0;
}
Output:
Alice is 30 years old. Bob is 25 years old. Charlie is 35 years old.
Advanced usage
Check whether a key exists:
if (myMap.find(key) != myMap.end()) {
// 键存在
}
Delete elements:
myMap.erase(key);
Clear map:
myMap.clear();
Get the size of the map:
size_t size = myMap.size();
Other methods:
myMap.empty(); // 是否为空
myMap.count("Bob"); // key 是否存在(返回 0 or 1)
For custom sorting, the default is ascending order; you can use std::greater or a custom comparison function:
std::map<int, std::string, std::greater<int>> m; // 降序
Use a custom comparison function:
Example
#include <string>
#include <functional>
bool myCompare(const std::string& a, const std::string& b) {
return a < b;
}
int main() {
std::map<std::string, int, std::function<bool(const std::string&, const std::string&)>> myMap(myCompare);
// Other operations...
return 0;
}
map is a very useful container in C++ STL, especially suitable for scenarios that require fast lookup and ordered data.
Example
#include <map>
#include <string>
int main() {
std::map<std::string, int> scores;
// Insert
scores["Alice"] = 90;
scores["Bob"] = 85;
scores.insert({"Charlie", 92});
// Traverse
for (auto &p : scores) {
std::cout << p.first << " => " << p.second << std::endl;
}
// Find
auto it = scores.find("Bob");
if (it != scores.end()) {
std::cout << "Bob's score: " << it->second << std::endl;
}
// Delete
scores.erase("Alice");
std::cout << "Size: " << scores.size() << std::endl;
return 0;
}
Running result (automatically sorted by key):
Alice => 90 Bob => 85 Charlie => 92 Bob's score: 85 Size: 2other extensions