目录
  • 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;
          }
      };

      总结

      声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。