繁体   English   中英

如何插入 boost::unordered_set <boost::unordered_set<int> &gt;? </boost::unordered_set<int>

[英]How do I insert into boost::unordered_set<boost::unordered_set<int> >?

以下代码无法编译,但如果我删除注释行,它会编译并正确运行。 我只打算使用 boost,因为 C++ 默认不为std::unordered_set<int>提供 hash function 。

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

int main() {
    boost::unordered_set<boost::unordered_set<int> > fam;
    boost::unordered_set<int> s;
    s.insert(5);
    s.insert(6);
    s.insert(7);
    std::cout << s.size() << std::endl;
    fam.insert(s); // this is the line causing the problem

    return 0;
}

编辑1:

我想比我在 OP 中更清楚。 首先我知道boost::unordered_set<>的想法是它是用 hash 表而不是 BST 实现的。 我知道任何要成为boost::unordered_set<>的模板类型的东西都需要提供 hash function 和平等 ZC1C425268E68385D1AB5074C17A94F14。 我也知道默认情况下std::unordered_set<>没有定义 hash function ,这就是以下代码无法编译的原因:

#include <iostream>
#include <unordered_set>

int main() {
    std::unordered_set<std::unordered_set<int> > fam;
    return 0;
}

但是,我认为 boost 为其所有容器提供了 hash 函数,这就是为什么我相信以下代码可以编译的原因:

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

int main() {
    boost::unordered_set<boost::unordered_set<int> > fam;
    return 0;
}

所以现在,我不确定为什么上面的 boost 代码可以编译,但 OP 中的代码却没有。 我错了 boost 为其所有容器提供 hash function 吗? 我真的很想避免定义一个新的 hash function,尤其是当我的实际预期用途是拥有更复杂的数据结构时: boost::unordered_map<std::pair<boost::unordered_map<int, int>, boost::unordered_map<int, int> >, int> 看来这应该是一个我不必定义自己的已解决问题,因为 IIRC python 可以处理成套集合没问题。

unordered_set (或_map )使用hashing ,并且需要为其元素定义 hash 运算符。 没有为boost::unordered_set<int>定义 hash 运算符,因此它不能将这种类型的元素放入您的集合中。

您可以为此编写自己的 hash function。 例如,这是一种典型的通用 hash 方法,尽管您可能希望针对您的特定数据对其进行自定义。 如果将此代码放入示例中,它应该可以工作:

namespace boost {
  std::size_t hash_value(boost::unordered_set<int> const& arg) {
    std::size_t hashCode = 1;
    for (int e : arg)
      hashCode = 31 * hashCode + hash<int>{}(e);
    return hashCode;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM