STL中unordered_map的常用方法

官方文檔有比本文更加全面的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;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章