C++中使用哈希表(unordered_map)的一些常用操作方法

Kara ·
更新时间:2024-09-20
· 596 次阅读

目录

1.建立基本数据类型的哈希表

2.向哈希表中添加元素

1).insert 函数

2).用数组方法直接添加

3.成员函数

begin(),end()函数

find()查找函数

count() 查找函数

size()函数

empty()函数

clear()函数

swap()函数

哈希表的遍历

第一种遍历

第二种遍历

补充:实际应用

总结

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 map 方法 哈希表 哈希 C++

需要 登录 后方可回复, 如果你还没有账号请 注册新账号