【cpp Trip第2站】map,set,hash
C++中的map、set和hash容器介绍
1. map(映射)
map是C++ STL中的关联容器,它存储键值对(key-value pairs),并根据键自动排序。
特点:
• 基于红黑树实现,保持元素有序
• 键唯一(不允许重复)
• 查找、插入、删除操作的时间复杂度为O(log n)
基本用法:
#include
std::map<std::string, int> ageMap;
// 插入元素
ageMap[“Alice”] = 25;
ageMap[“Bob”] = 30;
ageMap.insert({“Charlie”, 28});
// 访问元素
int aliceAge = ageMap[“Alice”];
// 遍历
for (const auto& pair : ageMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 查找
if (ageMap.find(“Bob”) != ageMap.end()) {
std::cout << “Bob found!” << std::endl;
}
变体:
• multimap:允许键重复的map
• unordered_map:基于哈希表的map,不排序,查找更快(平均O(1))
2. set(集合)
set是存储唯一元素的容器,元素自动排序。
特点:
• 基于红黑树实现
• 元素唯一且有序
• 查找、插入、删除操作的时间复杂度为O(log n)
基本用法:
#include
std::set numbers;
// 插入元素
numbers.insert(3);
numbers.insert(1);
numbers.insert(4);
// 遍历
for (int num : numbers) {
std::cout << num << " ";
}
// 查找
if (numbers.find(3) != numbers.end()) {
std::cout << “3 found in set” << std::endl;
}
变体:
• multiset:允许元素重复的set
• unordered_set:基于哈希表的set,不排序,查找更快(平均O(1))
3. hash(哈希表)
在C++中,哈希表主要通过unordered_map和unordered_set实现。
特点:
• 基于哈希表实现
• 元素无序
• 平均情况下查找、插入、删除操作的时间复杂度为O(1)
• 最坏情况下(哈希冲突严重)可能退化为O(n)
基本用法:
unordered_map:
#include <unordered_map>
#include
std::unordered_map<std::string, int> phonebook;
phonebook[“Alice”] = 123456;
phonebook[“Bob”] = 987654;
// 访问
int aliceNumber = phonebook[“Alice”];
// 遍历
for (const auto& entry : phonebook) {
std::cout << entry.first << ": " << entry.second << std::endl;
}
unordered_set:
#include <unordered_set>
std::unordered_setstd::string names;
names.insert(“Alice”);
names.insert(“Bob”);
if (names.count(“Alice”) > 0) {
std::cout << “Alice is in the set” << std::endl;
}
比较与选择
特性 map/set unordered_map/unordered_set
实现方式 红黑树 哈希表
元素顺序 有序 无序
查找性能 O(log n) 平均O(1),最坏O(n)
内存使用 通常较少 通常较多
适用场景 需要有序访问 需要快速查找,不关心顺序
选择建议:
• 如果需要元素有序,使用map/set
• 如果只需要快速查找,不关心顺序,使用unordered_map/unordered_set
• 如果数据量很大且哈希函数良好,哈希表通常性能更好