use*_*955 1 c++ templates unordered-map std c++11
我试图std::hash<T>通过提供专业化来扩展const char,以便我可以const char*用作键类型std::unordered_map.
这是我试过的:
#include <unordered_map>
#include <functional>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
namespace std
{
template<>
struct hash<const char*>
{
size_t operator()(const char* const& s) const
{
size_t h = 0;
const char* tmp = s;
while (*tmp)
h = (h << 5) + h + (unsigned char)toupper(*tmp++);
printf("hash of '%s' is (%ld)\n", s, h);
return h;
}
};
}
int main(int argc, char* argv[])
{
const char* name1= "Mark Nelson";
const char* name2= strdup(name1);
std::unordered_map<const char*, int> map;
printf("Insert (%s)\n", name1);
map[name1]= 100;
printf("Lookup (%s)\n", name1);
printf("map[%s](name1) = %d\n", name1, map.find(name1) != map.end() ? map.find(name1)->second : -1);
printf("Lookup (%s)\n", name2);
printf("map[%s](name2) = %d\n", name2, map.find(name2) != map.end() ? map.find(name2)->second : -1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是什么:
Insert (Mark Nelson)
hash of 'Mark Nelson' is (121066894705597050)
Lookup (Mark Nelson)
hash of 'Mark Nelson' is (121066894705597050)
hash of 'Mark Nelson' is (121066894705597050)
map[Mark Nelson](name1) = 100
Lookup (Mark Nelson)
hash of 'Mark Nelson' is (121066894705597050)
map[Mark Nelson](name2) = -1
Run Code Online (Sandbox Code Playgroud)
所以对我来说,似乎std::unordered_map是使用我提供的哈希实现插入和查找.但由于某种原因,它没有找到值via name2,这似乎仍然使用指针比较.
这有什么不对?我正在使用GCC 4.8.2,文件是用.编译的g++ -std=c++11 main.cc
无序地图需要两件事(参考):
所以你有(1)似乎工作,但然后地图必须检查const char *等于哪个转换为指针比较.为此,您可以指定自定义比较器(ref):
struct cmp_str
{
bool operator()(char const *a, char const *b)
{
return std::strcmp(a, b) == 0;
}
};
std::unordered_map<const char*, int, std::hash<const char *>, cmp_str> BlahBlah;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
395 次 |
| 最近记录: |