unordered_map 在 C++ 中是一个非常有用的容器,它允许你存储键值对,并且提供了基于键的快速查找。以下是一些 unordered_map 的用法举例:
- 基本操作
插入元素
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<std::string, int> myMap;
myMap["apple"] = 1;
myMap["banana"] = 2;
myMap["cherry"] = 3;
// 使用 insert 函数插入
myMap.insert(std::pair<std::string, int>("date", 4));
// 或者使用 make_pair
myMap.insert(std::make_pair("fig", 5));
return 0;
}
查找元素
if (myMap.find("banana") != myMap.end()) {
std::cout << "Found banana with value: " << myMap["banana"] << std::endl;
} else {
std::cout << "Banana not found" << std::endl;
}
访问元素
int value = myMap["apple"]; // 直接使用键访问值
std::cout << "Value of apple: " << value << std::endl;
删除元素
myMap.erase("cherry"); // 根据键删除元素
遍历元素
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
- 使用自定义类型和哈希函数
如果你想要使用自定义类型作为 unordered_map 的键,你需要为该类型提供一个哈希函数。以下是一个使用自定义类型和哈希函数的例子:
#include <iostream>
#include <unordered_map>
#include <functional> // for hash
struct Person {
std::string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
namespace std {
template<>
struct hash<Person> {
size_t operator()(const Person& p) const {
size_t h1 = hash<string>()(p.name);
size_t h2 = hash<int>()(p.age);
return h1 ^ (h2 << 1); // 合并哈希值
}
};
}
int main() {
std::unordered_map<Person, std::string> people;
people[Person{"Alice", 30}] = "Software Engineer";
people[Person{"Bob", 25}] = "Data Scientist";
for (const auto& entry : people) {
std::cout << "Name: " << entry.first.name << ", Age: " << entry.first.age
<< ", Occupation: " << entry.second << std::endl;
}
return 0;
}
在这个例子中,我们定义了一个 Person 结构体,并为它提供了一个哈希函数。这个哈希函数结合了 name 和 age 成员的哈希值来生成 Person 的唯一哈希值。然后,我们可以使用这个自定义类型作为 unordered_map 的键。
- 使用 Lambda 表达式作为查找条件
你还可以使用 find_if 算法和 lambda 表达式来基于更复杂的条件查找元素:
#include <iostream>
#include <unordered_map>
#include <algorithm>
int main() {
std::unordered_map<std::string, int> myMap;
myMap["apple"] = 1;
myMap["banana"] = 2;
myMap["cherry"] = 3;
// 使用 find_if 和 lambda 查找值大于 2 的元素
auto it = std::find_if(myMap.begin(), myMap.end(), [](const std::pair<std::string, int>& pair) {
return pair.second > 2;
});
if (it != myMap.end()) {
std::cout << "Found an element with value greater than 2: " << it->first << ",