在C++ STL中,哈希表的实现是使用unordered_map
和unordered_set
。它们都是基于哈希表实现的关联容器,提供了快速的插入、查找、删除等操作。在这里,我们将详细介绍unordered_map
和unordered_set
的常见函数。
目录
unordered_map
定义和声明
template < class Key, // unordered_map::key_type
class T, // unordered_map::mapped_type
class Hash = hash<Key>, // unordered_map::hasher
class Pred = std::equal_to<Key>, // unordered_map::key_equal
class Alloc = std::allocator< std::pair<const Key,T> > // unordered_map::allocator_type
> class unordered_map;
unordered_map
是一个模板类,用于定义哈希表,其中Key
是键类型,T
是值类型,Hash
是哈希函数的类型,Pred
是键比较函数的类型,Alloc
是分配器类型。在定义unordered_map
时,可以省略其中的一些参数,因为它们都有默认值。
插入和查找
unordered_map::insert()
unordered_map::emplace()
unordered_map::find()
unordered_map::count()
unordered_map::at()
insert()
:
插入一个键值对到哈希表中,如果键已经存在,会返回一个
pair
对象,其first
成员是指向已经存在的键值对的迭代器,其second
成员是false
。
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
myMap.insert({3, "pear"}); // 插入{3, "pear"}键值对到哈希表中
emplace()
:
使用给定的参数在哈希表中插入一个键值对,返回一个指向插入元素的迭代器。如果键已经存在,不会进行插入操作。
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
myMap.emplace(3, "pear"); // 插入{3, "pear"}键值对到哈希表中
find()
:
查找给定键对应的元素,返回一个指向该元素的迭代器,如果没有找到,返回一个指向哈希表尾部的迭代器。
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
auto it = myMap.find(2); // 返回指向{2, "banana"}的迭代器
count()
:
返回给定键对应的元素的个数,因为哈希表中每个键最多只有一个元素,所以返回值只能是0或1。
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
int num = myMap.count(1); // 返回1
删除:
unordered_map::erase()
unordered_map::clear()
erase()
:
删除给定键对应的元素,返回删除元素的个数,如果键不存在,返回0。
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
int num = myMap.erase(1); // 删除键为1的元素,返回1
clear()
:
删除哈希表中所有的元素
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
myMap.clear(); // 清空哈希表
遍历:
unordered_map::begin()
unordered_map::end()
unordered_map::cbegin()
unordered_map::cend()
unordered_map::size()
unordered_map::empty()
begin()
和end()
:
分别返回一个指向哈希表首元素和尾后元素的迭代器。
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << it->first << ": " << it->second << endl;
}
cbegin()
和cend()
:
返回一个指向哈希表首元素和尾后元素的
const
迭代器,不允许修改元素的值。
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
for (auto it = myMap.cbegin(); it != myMap.cend(); ++it) {
cout << it->first << ": " << it->second << endl;
}
size()
:
返回哈希表中元素的个数。
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}};
int num = myMap.size(); // 返回2
empty():
返回哈希表是否为空。
unordered_map<int, string> myMap;
if (myMap.empty()) {
cout << "The map is empty." << endl;
}