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是否已经存在。
  • 相关阅读:
    深入了解Struts2返回JSON数据的原理及具体应用范例
    Struts国际化
    LeetCode Balanced Binary Tree
    LeetCode Triangle
    Binary Tree Level Order Traversal
    Pow(x,n)
    Symmetric Tree
    LeetCode Word Search
    LeetCode Insert Interval
    Maximum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/maxwell-maxwill/p/15402127.html
Copyright © 2011-2022 走看看