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_mapunordered_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会极大提高程序效率
新闻热点
疑难解答