C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++使用哈希表(unordered_map)

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

作者:hero_th

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)内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文