【发布时间】:2020-07-28 15:10:10
【问题描述】:
查看下面的代码,我为 nocase-c-string key(const char*) 重载了 hash 函数和 string-equal 函数,但结果不是我所期望的:主函数将打印找不到,如何制作匹配吗?
struct hash_c_string
{
std::size_t operator()(const char *ctx) const
{
return MurmurHash2(ctx, strlen(ctx),static_cast<size_t>(0xc70f6907UL));
}
};
typedef struct {
const char * name;
}PortMapConfig;
struct by_name{};
struct CompareEqual
{
inline bool operator()(const char* left, const char* right) const
{
return strcasecmp(left, right)==0;
}
};
using namespace boost::multi_index;
typedef
boost::multi_index_container<
PortMapConfig,
indexed_by<
hashed_unique<tag<by_name>, member<PortMapConfig, const char *, &PortMapConfig::name>, hash_c_string, CompareEqual>
>
> StuContainer;
int main() {
StuContainer con;
PortMapConfig st1 = {"Uplink0"};
con.insert(st1);
auto &indexofName = con.get<by_name>();
const char * s = "uplink0";
auto itr = indexofName.find(s);
if(itr != indexofName.end()){
std::cout << "name:"<<itr->name << std::endl;
}
else
std::cout << "not found!!!"<< std::endl;
return 0;
}
【问题讨论】:
-
你的哈希函数和你的等价函数不匹配。等价函数忽略大小写,散列没有,所以两个等价的东西有不同的散列。行为未定义。
标签: c++ boost multi-index