声明具有免费功能的Unordered_set,以用于用户定义的哈希和比较



此代码使用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,您可以使用decltypestd::function

可以将绑定对象存储在 std::function

typedef std::unordered_set<int,
    std::function<size_t(int)>, std::function<bool(int, int)>> NewSet;
NewSet newSet (
    10,
    std::bind ( IntHash, std::placeholders::_1 ),
    std::bind ( IntComp, std::placeholders::_1, std::placeholders::_2 ) );

std::functionstd::pointer_to_unary_function等的替代品:

typedef std::unordered_set<int, 
                std::function<size_t(int)>,
                std::function<bool(int,int)>> NewSet;

所有这些函数已被std::function弃用。(尽管如评论中所述,等等。常规函数指针在此处是可取的,因为std::function旨在存储任何类型的可呼叫实体)。

最新更新