官方文档有比本文更加全面的API说明:
http://www.cplusplus.com/reference/unordered_map/unordered_map/
以下主要记录一些最常用的API:
#include<unordered_map>
using namespace std;
int main()
{
unordered_map <string, int> hash;
//以下是三种插入键值对的方法
hash["Apple"] = 1; //如果原先没有该pair,则会插入该pair。如果有,则会修改value值
hash.insert(make_pair("Orange", 2));
hash.insert(pair<string,int>("Banana", 3));
//以下是两种查找key是否存在于unordered_map的方法
if (hash.find("Apple") != hash.end()) //方法一:查找key是否在map中
cout << "Apple exists"<<endl;
if (hash.count("Banana") != 0) //方法二:查找key是否在map中
cout << "Banana exists" << endl;
//以下是两种遍历key和value的方式
for (auto iter = hash.begin(); iter != hash.end(); ++iter)
cout << "first :" << iter->first << "second :" << iter->second << endl;
for (auto element : hash)
cout << "first :" << element.first << "second :" << element.second << endl;
}