unordered_map是C++标准库中的容器类,类似于Java中的HashMap或Python中的字典。它提供了一种存储键值对的方式,可以快速地查找和访问值。
使用unordered_map的步骤如下:
包含头文件:#include <unordered_map>创建unordered_map对象:std::unordered_map<Key, T> unordered_map_name;,其中Key是键的类型,T是值的类型。插入键值对:unordered_map_name[key] = value;,或者使用insert()函数:unordered_map_name.insert(std::make_pair(key, value));查找值:unordered_map_name[key],返回键对应的值。删除键值对:使用erase()函数:unordered_map_name.erase(key);判断键是否存在:使用count()函数:unordered_map_name.count(key),返回0表示不存在,1表示存在。遍历unordered_map:可以使用迭代器进行遍历:for(auto it = unordered_map_name.begin(); it != unordered_map_name.end(); ++it) { // 遍历操作,it->first表示键,it->second表示值}unordered_map的特点是:
键是唯一的,重复的键只会插入一次。键和值可以是任意类型。根据键的哈希值进行存储,因此插入和访问的时间复杂度是常数时间O(1)。元素的顺序是不确定的,不会按照插入的顺序进行排列。需要注意的是,使用unordered_map需要包含头文件<unordered_map>,并使用std命名空间。

