c++ - 使用自由函数声明 unordered_set 用于用户定义的散列和比较

标签 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 );
}

不过,我不想使用已弃用的 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 );
}

这无法编译,我想是因为我不确定要为 UserDefinedHashUserDefinedComparison 添加什么。

看起来 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

关于c++ - 使用自由函数声明 unordered_set 用于用户定义的散列和比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13077321/

相关文章:

c++ - 为什么元组有 uses_allocator 而对却没有?

c++ - Qt Creator编译错误 "::swprintf and::vswprintf has not been declared"

c++ - strdup 指针版本需要一个临时指针

c++ - Win32 中的 RedrawWindow 和 UpdateWindow 有什么区别?

c++ - 访问被拒绝后,c++中的故障安全代码

c++ - struct 中的 vector 指针无法转换 main 中的 vector ,这是怎么回事?

c++ - std::iostream 读取或写入计数为零且缓冲区无效

c++ - 将 memcpy 与 vector 的 unique_ptr 结合使用

c++ - 如何获得 "bus error"?

c++ - 在 C++11 中从 std::deque move 一个元素