vs2010中的stdext::hash_map在vs2015下的问题

vs2010中的hash_map调用方式:

需要头文件<hash_map>和命令空间stdext,且需要为不同key类型定义相应的comparator

#include <hash_map>
using namespace stdext;


struct intLess : public std::binary_function<const int, const int, bool>
{
public:
    result_type operator()(const first_argument_type& _Left, const second_argument_type& _Right) const
    {
        return _Left == _Right;
    }
};

struct charLess : public std::binary_function<const char*, const char*, bool>
{
public:
    result_type operator()(const first_argument_type& _Left, const second_argument_type& _Right) const
    {
        return(_stricmp(_Left, _Right) < 0 ? true : false);
    }
};

这样就产生了一个要命的问题:hash_map的key必须为const。这个要求只有在vs2012之前版本才有;gcc我碰到的版本都没有。

如果你用新版本,比如vs2015,那么就会碰到这种编译错误:

Microsoft Visual Studio 14.0\VC\INCLUDE\xstddef(377): error C2338: The C++ Standard doesn't provide a hash for this type.

原因就是这个const不再需要了,另外C++11已经添加了std::unordered_map,且不需要自己实现了comparator,使用起来比旧版的hash_map更方便。微软设计一些反人类的api也够坑的。

总结:
除了vs2010下的stdext::hash_map的key需要为const外,其他情况下的map都不需要为const,其中std::unordered_map的key必须不能为const,std::map可以为const也可以不为const。

猜你喜欢

转载自aigo.iteye.com/blog/2293779