【问题标题】:How to use boost hash_value in std unordered_set?如何在 std unordered_set 中使用 boost hash_value?
【发布时间】:2021-06-23 17:24:38
【问题描述】:

如何在不定义仿函数的情况下在std::unordered_set<std::pair<>> 中使用boost::hash_value<std::pair<>>

以下不起作用:

        typedef std::pair<unsigned, unsigned> S;

        typedef size_t (hash_value_sample)(const S&);
        std::function<hash_value_sample> hasher = 
                    static_cast<hash_value_sample&>(boost::hash_value<unsigned, unsigned>);

        std::unordered_set<S, decltype(hasher)> set;
        set.insert(S(10, 10));

执行中止。

terminate called after throwing an instance of 'std::bad_function_call'
  what():  bad_function_call
Abort

我认为上述方法不起作用,因为 hasher() 不存在。我正在使用 g++ -std=c++14

【问题讨论】:

标签: c++ boost unordered-set


【解决方案1】:

根据我的测试,这似乎有效:

#include <iostream>
#include <unordered_set>
#include <boost/functional/hash.hpp>

typedef std::pair<unsigned, unsigned> S;
typedef boost::hash<S> hash_t;

int main() {
  std::unordered_set<S, hash_t> set;
  set.insert(S(10, 10));
  std::cout << set.count(S(10, 10)) << std::endl;
  std::cout << set.count(S(10, 9)) << std::endl;
  return 0;
}

输出:

❯ clang++ test.cpp -o test && ./test
1
0

【讨论】:

  • 让我重新表述我的问题。如果我有一个现有的散列函数,那么如何在 STL 关联容器中使用它而不将它包含在新的仿函数中?
  • @user3689963 你没有。这个答案也没有:using 没有引入新类型,标准的hash&lt;&gt; 特化被内联(与std::hash&lt;&gt; 相同)
【解决方案2】:

你可以用 lambda 来做到这一点:

auto hasher = [] (S s) { return boost::hash_value (s); };
std::unordered_set<S, decltype(hasher)> set;

Live demo

【讨论】:

  • 仅从 c++20 开始工作,其中 lambda 是默认可构造的。
  • @rafix07 哦,是的...好吧,也许 OP 可以使用它。
  • @rafix07 你已经更快了:wandbox.org/permlink/3fmBWivrTSBGsOAE
猜你喜欢
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
  • 2014-05-05
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多