hash_map,unordered_map的使用

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
    {
        size_t operator()(long long x) const
        {
            return x;
        }
    };
}

c++代码使用样例

#include
#include
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
    {
        size_t operator()(long long x) const
        {
            return x;
        }
    };
}
using namespace std;
using  namespace __gnu_cxx;
int main()
{
    hash_mapa;
    hash_mapb;
    return 0;
}

unordered_map

unordered_map是C++11的新特性支持string和long long,和hash_map类似,就不在多解释了,已经引入标准库函数,推荐使用。

需要使用std::tr1命名空间

C++代码使用

#include
#include
using namespace std;
using  namespace std::tr1;
int main()
{
    unordered_mapa;
    return 0;
}



至于set,multiset和multimap,内容和map类似,这里就不在赘述;

按照情况利用hash_map和map会极大提高程序效率





你可能感兴趣的:(容器,STL,hash,数据处理,STL)