c++ - Can I use lambda as a hashing function in boost::multi_index hash-like interface?
问题描述
Is it possible to use lambda for hashing in hashed_<non>_unique interface for boost::multi_index? See this example: https://godbolt.org/z/1voof3
I also saw this: How to use lambda function as hash function in unordered_map? where the answer says:
You need to pass lambda object to unordered_map constructor since lambda types are not default constructible.
and I'm not sure is it even possible to do for the given example on godbolt.
解决方案
Starting with C++20, yes, you can: https://godbolt.org/z/fTbzPP (note f
is declared as auto const hash_f
, without a &
).
As for @sehe's claim that multi_index_container
s can't be passed instances of hash objects (or other intervening function objects) at construction time, the claim is incorrect: they can, although the interface is somewhat complicated:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <functional>
struct non_default_ctble_hash
{
non_default_ctble_hash(std::size_t n):n{n}{}
template<typename T>
std::size_t operator()(const T& x){return std::hash<T>{}(x)*n;}
std::size_t n;
};
using namespace boost::multi_index;
using container=multi_index_container<
int,
indexed_by<
hashed_unique<identity<int>,non_default_ctble_hash>
>
>;
int main()
{
container::ctor_args_list cal{
{0,identity<int>{},non_default_ctble_hash{666},std::equal_to<int>{}}
};
container c(cal);
}
推荐阅读
- python-3.x - Python程序在for循环完成后停止,里面有输入
- f# - 如何避免 F# Seq.map 中的自动排序
- python - 如何在 Linux 命令行中从 artifactory 获取 MD5 校验和
- python - 在我的 django 应用程序中出现错误“ModuleNotFoundError: No module named 'django.wsgi'”。我有这个错误。我无法修复它
- botframework - 如何使用 botbuilder v4 nodejs 向所有团队用户发送主动消息
- php - AMP:是否可以始终使用 amp-user-notification 显示通知?
- java - 如何配对在同一图像的多个 docker 容器中运行的嵌入式 Hazelcast
- python - 如何从熊猫数据框中获取默认索引
- node.js - 有没有办法通过 DirectLine API 和使用 Oauth2.0 抽象的 Azure Web 应用程序对 Microsoft Bot 框架网络聊天进行单点登录
- javascript - 嵌套的链接元素不会重定向到 React 中的组件