gpt4 book ai didi

c++ - 使用 lambda 做定义哈希函数抛出异常

转载 作者:行者123 更新时间:2023-11-30 02:57:11 24 4
gpt4 key购买 nike

下面的代码定义了一个unordered_set。代码编译得很好。但是在调用 find 时使用 lambda 函数而不是 functor throw:

libc++abi.dylib: terminate called throwing an exception

#include <unordered_set>

class pair_hash {
public:
size_t operator() (const std::pair<int, int> &x) const {
return std::hash<int>()(x.first) ^ std::hash<int>()(x.second);
}
};

int main() {
std::unordered_set<std::pair<int, int>, pair_hash> temp;
temp.find(std::make_pair(0,0));


std::function<std::size_t(std::pair<int , int>)> fpair_hash;
fpair_hash = [](const std::pair<int, int>& v) -> std::size_t
{
return std::hash<int>()(v.first) ^ std::hash<int>()(v.second);
};

std::unordered_set<std::pair<int, int>, decltype(fpair_hash)> temp2;
//why does this not work?
temp2.find(std::make_pair(0,0));
return 0;
}

clang++ -std=c++11 -stdlib=libc++ -o test test.cpp

最佳答案

decltype(fpair_hash)std::function<std::size_t(std::pair<int , int>)>所以你只是用空哈希函数构建集合。

您需要将您的函数提供给 std::unordered_set 的构造函数:

std::unordered_set<std::pair<int, int>, decltype(fpair_hash)> temp2(10, fpair_hash);

这应该可以让它工作,但是使用 std::function会有多态调用的开销,你可能不需要它:

auto fpair_hash = [](const std::pair<int, int>& v) -> std::size_t
{
return std::hash<int>()(v.first) ^ std::hash<int>()(v.second);
};

最后,你的散列函数不是很好 - 它映射所有对 (x, x)0 .也许使用类似 x * 17 + y * 13 的东西而不是 x ^ y将减少碰撞的可能性。

关于c++ - 使用 lambda 做定义哈希函数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14841528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com