zoukankan      html  css  js  c++  java
  • Hashmap

    Map

    Map就是存储key-value对.

    #include <string>
    #include <iostream>
    #include <map>
    using namespace std;
    
    void Printmap(string comment, map<string, int> &m){
       cout<<comment<<" ";
       for(auto iter= m.begin();iter!=m.end();iter++){
          cout<<iter->first<<"="<<iter->second<<";";
       }
       cout<<endl;
    }
    
    int main () {
       map<string, int> m = {{"cpu",10},{"gpu",20}};
       Printmap("Intial Map is:",m);
       m["ssd"]=100;
       Printmap("updated Map is:",m);
       return 0;
    }
    

    使用起来非常简单。iter->first是key,iter->second是value.可以使用iterator遍历。可以使用key查找value。

    Hashmap

    自己写的论文里早用过啦,来看一下STL中的用法。

    #include <iostream>
    #include <unordered_map>
    #include <string>
    using namespace std;
    
    int main () {
       unordered_map<string, int> u = {
          {"a",1},{"b",2},{"c",3}
       };
       for(auto iter=u.begin();iter!=u.end();iter++){
          cout<<iter->first<<" "<<iter->second<<";";
       }
       cout<<endl;
       cout<<u.count("k")<<endl;
    }
    

    几个注意的点:

    1. unordered_map顾名思义,是无序的。而map是基于二叉查找树的,是有序的。
    2. u.count(key)统计相应的key有几个(0或1),可以用来确认key是否已经存在。
  • 相关阅读:
    习惯的本质:逐步建立新的常态
    如何度过有用的每一天
    如何利用晚上八点到十点这段时间自我提升
    为什么很多年轻人总会感到迷茫
    当你学会专注,人生才算真正成熟
    如何过上简单的生活
    游标
    触发器

    函数
  • 原文地址:https://www.cnblogs.com/maxwell-maxwill/p/15402127.html
Copyright © 2011-2022 走看看