C++ STL中的set,multiset,map和multimap實現(xiàn)基于紅黑樹,插入和查找的復雜度均為logn
hash_map
和map不同的是hash_map是基于哈希表實現(xiàn)的,查找復雜度位o(1),插入略慢,還沒有測試,插入后不進行自動排序
使用命名空間__gnu_cxx
hash_map不是標準的庫,對std::string和long long的支持有點問題
如果要用string和long long需要做以下修改
使用string
namespace __gnu_cxx{ template<> struct hash< std::string > { size_t Operator()( const std::string& x ) const { return hash< const char* >()( x.c_str() ); } };}使用long long
namespace __gnu_cxx{ template<> struct hash<long long> { size_t operator()(long long x) const { return x; } };}c++代碼使用樣例#include<iostream>#include<hash_map>namespace __gnu_cxx{ template<> struct hash< std::string > { size_t operator()( const std::string& x ) const { return hash< const char* >()( x.c_str() ); } };template<> struct hash<long long> { size_t operator()(long long x) const { return x; } };}using namespace std;using namespace __gnu_cxx;int main(){ hash_map<string,int>a; hash_map<long long,long long>b; return 0;}unordered_mapunordered_map是C++11的新特性支持string和long long,和hash_map類似,就不在多解釋了,已經(jīng)引入標準庫函數(shù),推薦使用。
需要使用std::tr1命名空間
C++代碼使用
#include<iostream>#include<tr1/unordered_map>using namespace std;using namespace std::tr1;int main(){ unordered_map<string,long long>a; return 0;}至于set,multiset和multimap,內(nèi)容和map類似,這里就不在贅述;
按照情況利用hash_map和map會極大提高程序效率
新聞熱點
疑難解答