隨著C++0x標準的確立,C++的標準庫中也終于有了hash table這個東西。
很久以來,STL中都只提供<map>作為存放對應關系的容器,內部通常用紅黑樹實現,據說原因是二叉平衡樹(如紅黑樹)的各種操作,插入、刪除、查找等,都是穩定的時間復雜度,即O(log n);但是對于hash表來說,由于無法避免re-hash所帶來的性能問題,即使大多數情況下hash表的性能非常好,但是re-hash所帶來的不穩定性在當時是不能容忍的。
不過由于hash表的性能優勢,它的使用面還是很廣的,于是第三方的類庫基本都提供了支持,比如MSVC中的<hash_map>和Boost中的<boost/unordered_map.hpp>。后來Boost的unordered_map被吸納進了TR1 (C++ Technical Report 1),然后在C++0x中被最終定了標準。
于是我們現在就可以開心得寫以下的代碼了:
#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;}
新聞熱點
疑難解答
圖片精選