我可以在boost::multi_index类似散列的接口中使用lambda作为散列函数吗



是否可以在hashed<非&gt_boost::multi_index的唯一接口?请参见此示例:https://godbolt.org/z/1voof3

我还看到了以下内容:如何在unrdered_map中使用lambda函数作为哈希函数?答案是:

您需要将lambda对象传递给unordered_map构造函数,因为lambda类型不是默认的可构造类型。

,我不确定是否有可能在godbolt上为给定的例子做这件事。

从C++20开始,是的,您可以:https://godbolt.org/z/fTbzPP(注意,f被声明为auto const hash_f,没有&(。

至于@sehe声称multi_index_containers在构建时不能被传递哈希对象(或其他介入函数对象(的实例,这种说法是不正确的:它们可以,尽管接口有点复杂:

Coliru现场演示

#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);
}

我认为你做不到。对于标准容器,您必须将实际实例提供给构造函数。然而,MultiIndex负担不起:

文档

正如索引概念部分所解释的,索引没有公共构造函数或析构函数。另一方面,提供了转让。构造时,max_load_factor((为1.0。

漏洞

您也许可以使用本地定义的类:

auto const hash_f = [](int const& n) { return std::hash<int>()(n); };
struct HashType : decltype(hash_f) {};
using AnimalsMultiIndex = multi_index_container<
Animal, indexed_by<hashed_non_unique<
tag<animal_legs>, member<Animal, LegsType, &Animal::legs>,
HashType>>>;
AnimalsMultiIndex animals;

哪个有效:c++20需要

#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/tag.hpp>
#include <boost/multi_index_container.hpp>
#include <iostream>
#include <string>
using namespace boost::multi_index;
using LegsType = int;
struct Animal {
std::string name;
LegsType legs;
};
// tags
struct animal_legs {};
int main() {
// using lambda doesn't work for hashing
auto const hash_f = [](int const& n) { return std::hash<int>()(n); };
struct HashType : decltype(hash_f) {};
using AnimalsMultiIndex = multi_index_container<
Animal, indexed_by<hashed_non_unique<
tag<animal_legs>, member<Animal, LegsType, &Animal::legs>,
HashType>>>;
AnimalsMultiIndex animals;
animals.insert({ "cat", 4 });
auto const& legs_index = animals.get<animal_legs>();
int num_of_legs = 4;
std::cout << "Number of animals that have " << num_of_legs
<< " legs is: " << legs_index.count(num_of_legs) << 'n';
}

打印

Number of animals that have 4 legs is: 1

最新更新