C++中的哈希容器unordered_map使用示例
隨著C++0x標(biāo)準(zhǔn)的確立,C++的標(biāo)準(zhǔn)庫中也終于有了hash table這個(gè)東西。
很久以來,STL中都只提供<map>作為存放對(duì)應(yīng)關(guān)系的容器,內(nèi)部通常用紅黑樹實(shí)現(xiàn),據(jù)說原因是二叉平衡樹(如紅黑樹)的各種操作,插入、刪除、查找等,都是穩(wěn)定的時(shí)間復(fù)雜度,即O(log n);但是對(duì)于hash表來說,由于無法避免re-hash所帶來的性能問題,即使大多數(shù)情況下hash表的性能非常好,但是re-hash所帶來的不穩(wěn)定性在當(dāng)時(shí)是不能容忍的。
不過由于hash表的性能優(yōu)勢(shì),它的使用面還是很廣的,于是第三方的類庫基本都提供了支持,比如MSVC中的<hash_map>和Boost中的<boost/unordered_map.hpp>。后來Boost的unordered_map被吸納進(jìn)了TR1 (C++ Technical Report 1),然后在C++0x中被最終定了標(biāo)準(zhǔn)。
于是我們現(xiàn)在就可以開心得寫以下的代碼了:
#include <iostream> #include <string> #include <unordered_map> int main() { std::unordered_map<std::string, int> months; months["january"] = 31; months["february"] = 28; months["march"] = 31; months["april"] = 30; months["may"] = 31; months["june"] = 30; months["july"] = 31; months["august"] = 31; months["september"] = 30; months["october"] = 31; months["november"] = 30; months["december"] = 31; std::cout << "september -> " << months["september"] << std::endl; std::cout << "april -> " << months["april"] << std::endl; std::cout << "december -> " << months["december"] << std::endl; std::cout << "february -> " << months["february"] << std::endl; return 0; }
相關(guān)文章
C語言如何把浮點(diǎn)數(shù)轉(zhuǎn)換為字符串
這篇文章主要介紹了C語言如何把浮點(diǎn)數(shù)轉(zhuǎn)換為字符串方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12基于C++實(shí)現(xiàn)kinect+opencv 獲取深度及彩色數(shù)據(jù)
本文的主要思想是Kinect SDK 讀取彩色、深度、骨骼信息并用OpenCV顯示,非常的實(shí)用,有需要的小伙伴可以參考下2015-12-12C++如何計(jì)算結(jié)構(gòu)體與對(duì)象的大小
這篇文章主要給大家介紹了關(guān)于C++如何計(jì)算結(jié)構(gòu)體與對(duì)象大小的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05