声明具有免费功能的Unordered_set,以用于用户定义的哈希和比较
Declaring unordered_set with free functions for user-defined hash and comparison
此代码使用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
旨在存储任何类型的可呼叫实体)。
相关文章:
- 专用于 std 元组的模板,而无需用户执行remove_cvref
- 用于获取枚举值的用户输入
- 是否可以在运行时调用用于选择要调用的用户定义文本的逻辑?
- 表达式模板玩具示例:用户定义的强制转换不适用于复杂类型
- C++代码,用于在用户插入的字符串的每个元音之后插入一对字符
- 用户定义的转换不适用于可变参数函数参数?为什么不呢?
- 用户指定的参数,用于确定在大循环中调用哪个函数
- 用于在C++中计算用户数据的线程
- 指定在用户固定我的应用程序时用于运行应用程序的命令参数
- C++ 将用户输入数据用于多个函数
- std::sort 不适用于带有 oveload <运算符的用户定义对象
- 如何使用用户输入正确修改 2D 数组中的字符数组元素?专门用于电影院座位
- 用户定义的转换运算符不适用于引用
- 将 std 库函数专门用于用户定义类型的shared_ptr是否合法?
- 拥有用于QT应用程序的Web用户界面的最佳方法
- C 17:始终调用用户定义的构造函数,并且运算符 超载不适用于儿童课程
- 奇怪的用户定义的比较结构错误,用于C++中的priority_queue
- 用户定义的功能用于竞争编程中,以获取输入
- 智能指针的成员初始化列表,用于用户定义的结构
- 用户用于输入程序设置的文件约定