微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我可以在 boost::multi_index 类哈希接口中使用 lambda 作为哈希函数吗?

如何解决我可以在 boost::multi_index 类哈希接口中使用 lambda 作为哈希函数吗?

是否可以在 boost::multi_index 的 hashed_<non>_unique 接口中使用 lambda 进行散列? 请参阅此示例:https://godbolt.org/z/1voof3

我也看到了这个:How to use lambda function as hash function in unordered_map? 答案是:

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

而且我不确定是否有可能对 Godbolt 上的给定示例进行操作。

解决方法

我不认为你可以。使用标准容器,您必须向构造函数提供实际实例。但是,MultiIndex 负担不起:

docs

index concepts section 中所述,索引没有公共构造函数或析构函数。另一方面,提供了赋值。构建时,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 required

#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>,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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。