这段代码可以在 g++ 4.4 和“-std=c++0x”下正常编译。
#include <unordered_set>
namespace
{
size_t IntHash ( int i )
{
return i;
}
bool IntComp ( int i, int j )
{
return i == j;
}
}
int main ( int argc, char* argv[] )
{
typedef std::pointer_to_unary_function<int, size_t> CustomHash;
typedef std::pointer_to_binary_function<int, int, bool>
CustomComp;
typedef std::unordered_set<int, CustomHash, CustomComp> DeprecatedSet;
DeprecatedSet deprecatedSet ( 10, std::ptr_fun ( IntHash ), std::ptr_fun ( IntComp ) );
deprecatedSet.insert ( 5 );
deprecatedSet.insert ( 10 );
}
不过,我不想使用已弃用的 std::pointer_to_unary_function 和 std::ptr_fun,但仍使用免费函数:
#include <unordered_set>
#include <functional>
namespace
{
size_t IntHash ( int i )
{
return i;
}
bool IntComp ( int i, int j )
{
return i == j;
}
}
int main ( int argc, char* argv[] )
{
typedef std::unordered_set<int /*, UserDefinedHash?, UserDefinedComparison? */> NewSet;
NewSet newSet (
10,
std::bind ( IntHash, std::placeholders::_1 ),
std::bind ( IntComp, std::placeholders::_1, std::placeholders::_2 ) );
newSet.insert ( 5 );
newSet.insert ( 10 );
}
这无法编译,我想是因为我不确定要为 UserDefinedHash 和 UserDefinedComparison 添加什么。
看起来 std::bind 没有定义 bind 对象本身类型的成员类型。
我知道还有其他方法可以定义自定义哈希函数和比较,只是好奇是否可以在不推荐使用标准库类型和函数的情况下使用自由/类函数。
最佳答案
您可以使用:
std::unordered_set<int, size_t(*)(int), bool(*)(int, int)> my_set;
my_set s( 10, &IntHash, &IntComp );
并且为了使用std::bind
,您可以使用decltype
或std::function
关于c++ - 使用自由函数声明 unordered_set 用于用户定义的散列和比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13077321/