C++标准库中使用的unordered_map底层实现是哈希表,下面这篇文章主要给大家介绍了关于C++中使用哈希表(unordered_map)的一些常用操作方法,需要的朋友可以参考下
1.建立基本数据类型的哈希表
unordered_map<int,int> m; //<string,string>,<char,char>
2.向哈希表中添加元素
1).insert 函数
m.insert(pair<int,int>(1, 10));
m.insert(pair<int,int>(2, 20));
2).用数组方法直接添加
m[3]=30;
m[4]=40;3.成员函数
begin(),end()函数
m.begin() //指向哈希表的第一个容器
m.end() //指向哈希表的最后一个容器,实则超出了哈希表的范围,为空
find()查找函数
m.find(2) //查找key为2的键值对是否存在 ,若没找到则返回m.end()
if(m.find(2)!=m.end()) //判断找到了key为2的键值对
count() 查找函数
查找哈希表中key为3的键值对,返回其数量,为1,则找到,若没找到则返回0
m.count(3) //返回 1
m.count(5) //返回0
size()函数
m.size() //返回哈希表的大小
empty()函数
m.empty() //判断哈希表是否为空,返回值为true/false
clear()函数
m.clear() //清空哈希表
swap()函数
交换两个哈希表中的元素,整个哈希表的键值对全部都交换过去
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;
}
};总结
到此这篇关于C++中使用哈希表(unordered_map)的常用操作的文章就介绍到这了,更多相关C++使用哈希表(unordered_map)内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:C++中使用哈希表(unordered_map)的一些常用操作方法
- C语言qsort()函数的使用方法详解 2023-04-26
- ubuntu下C/C++获取剩余内存 2023-09-18
- C++ 数据结构超详细讲解顺序表 2023-03-25
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- Qt计时器使用方法详解 2023-05-30
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- C语言详解float类型在内存中的存储方式 2023-03-27
- Easyx实现扫雷游戏 2023-02-06
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
