使用用于用户定义的哈希和比较的自由函数声明unordered_set

Joe*_*yle 2 c++ c++11

这段代码用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 );
}
Run Code Online (Sandbox Code Playgroud)

但是,我不想使用已弃用的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 );
}
Run Code Online (Sandbox Code Playgroud)

这不编译,我假设因为我不确定要为UserDefinedHashUserDefinedComparison投入什么.

它看起来不像std :: bind有一个定义绑定对象本身类型的成员类型.

我知道还有其他方法来定义自定义散列函数和比较,只是好奇是否可以使用自由/类函数而不使用已弃用的标准库类型和函数.

Big*_*oss 10

您可以使用:

std::unordered_set<int, size_t(*)(int), bool(*)(int, int)> my_set;
my_set s( 10, &IntHash, &IntComp );
Run Code Online (Sandbox Code Playgroud)

并且为了使用std::bind,您可以使用decltypestd::function