unordered_map<int,int> m; //<string,string>,<char,char>
m.insert(pair<int,int>(1, 10)); m.insert(pair<int,int>(2, 20));
m[3]=30; m[4]=40;
m.begin() //指向哈希表的第一个容器 m.end() //指向哈希表的最后一个容器,实则超出了哈希表的范围,为空
m.find(2) //查找key为2的键值对是否存在 ,若没找到则返回m.end() if(m.find(2)!=m.end()) //判断找到了key为2的键值对
查找哈希表中key为3的键值对,返回其数量,为1,则找到,若没找到则返回0

m.count(3) //返回 1 m.count(5) //返回0
m.size() //返回哈希表的大小
m.empty() //判断哈希表是否为空,返回值为true/false
m.clear() //清空哈希表
交换两个哈希表中的元素,整个哈希表的键值对全部都交换过去
unordered_map<int,int> m1; unordered_map<int,int> m2; m1.swap(m2); swap(m1,m2);
unordered_map<int, int> count;
for (auto p : count) {
int front = p.first; //key
int end = p.second; //value
}
unordered_map<int, int> count;
for(auto it=m.begin();it!=m.end();it++)
{
int front = it->first; //key
int end = it->second; //value
}
LeetCode的242题:有效的字母异位词
题目描述:
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-anagram
具体的分析可以去看LeetCode上面的优质解答,那上面的最高赞,或者关注的人比较多的答案基本都是很优秀的解答和分析。这个问题的解法其中一个就是使用了unordered_map进行解决的:
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
unordered_map<char, int> umap;
for (int i = 0; i < s.size(); ++i) {
umap[s[i]]++;
umap[t[i]]--;
}
for (auto ch : umap) {
if (ch.second != 0) {
return false;
}
}
return true;
}
};