首先需要包含头文件
#include <unordered_map>
using namespace std;
unordered_map在< >中需要指明两个变量类型,第一个是key的类型,第二个是key对应的value的类型
可以单次定义:
unordered_map<char, int> map;
map['A'] = 1;
也可以多个键值对一起定义:
unordered_map<char, int> map={
{'A',1},
{'B',2},
{'C',3}
};
哈希表类型也可以更改,比如 key 和 value 都是 char 类型:
unordered_map<char, char> map={
{')','('},
{']','['},
{'}','{'}
};
在调用哈希表时,注意使用方括号,而不是圆括号
cout << map['A'];
如果需要判断某 key 是否存在于哈希表中,可以使用 count() 函数。
count()返回要查找的key在map的所有key种的出现次数。因为此容器不允许重复,故count()只可能返回 1 或 0,即可判断此key是否存在。
if (map.count('A')) {
cout << "I'm here";
}
else {
cout << "I'm not here";
}
另外,还可以使用 find() 函数实现上述功能:
if (map.find('A')==map.end()) {
cout << "I'm not here";
}
else {
cout << "I'm here";
}
猜你喜欢:👇🏻
⭐【C++】判断字符串长度是奇数还是偶数
⭐【C++】cout 换行或空格输出两个数
⭐【C++】构建栈 进栈和出栈