此代码使用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
可以将绑定对象存储在 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::function
是std::pointer_to_unary_function
等的替代品:
typedef std::unordered_set<int,
std::function<size_t(int)>,
std::function<bool(int,int)>> NewSet;
所有这些函数已被std::function
弃用。(尽管如评论中所述,等等。常规函数指针在此处是可取的,因为std::function
旨在存储任何类型的可呼叫实体)。