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