C++ STL中的set,multiset,map和multimap實現基於紅黑樹,插入和查找的複雜度均爲logn
hash_map
和map不同的是hash_map是基於哈希表實現的,查找複雜度位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_map
unordered_map是C++11的新特性支持string和long
long,和hash_map類似,就不在多解釋了,已經引入標準庫函數,推薦使用。
需要使用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,內容和map類似,這裏就不在贅述;
按照情況利用hash_map和map會極大提高程序效率