1

我正在尝试使用例如类型创建一个STL(或boostunordered_map,但在尝试将元素插入此容器后抛出错误。boost::mulprecisioncpp_intgcc

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/unordered_map.hpp>

using namespace boost::multiprecision;

int main()
{
  cpp_int z(123123123);
  cpp_int x(123123123);

  boost::unordered_map<cpp_int, cpp_int> data;

  // line below will throw compilation errors
  //data.insert(std::make_pair(z,x));
  return 0;
}

完整的错误日志在这里

第一个错误:

In file included from /usr/include/boost/functional/hash/hash.hpp:529:0,
                 from /usr/include/boost/functional/hash.hpp:6,
                 from /usr/include/boost/unordered/unordered_map.hpp:20,
                 from /usr/include/boost/unordered_map.hpp:16,
                 from main.cpp:2:
/usr/include/boost/functional/hash/extensions.hpp: In instantiation of
  ........
main.cpp:13:34:   required from here
/usr/include/boost/functional/hash/extensions.hpp:269:34: error: no matching function for call to ‘hash_value(const boost::multiprecision::number<boost::multiprecision::backends::cpp_int_backend<> >&)’
             return hash_value(val);
                                  ^

关于的多精度类型, STL/boost容器的使用是否有限制?boost我正在使用提升 1.54。

编辑

这可能是重复使用的问题boost::multiprecision是在 boost 1.56 中添加的序列化支持(至少根据文档@1.55@1.56的差异。

此外,在那个问题中,没有提到在没有序列化支持的情况下解决此问题的其他方法boost::multiprecision

4

1 回答 1

3

您的“这可能是重复的问题”在问题本身中记录了一种工作技术 - 散列字符串表示:

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/unordered_map.hpp>

using namespace boost::multiprecision;

template <typename T>
struct hash_str
{
    size_t operator()(const T& t) const { return std::hash<std::string>()(t.str()); }
};

int main()
{
  cpp_int z(123123123);
  cpp_int x(123123123);

  boost::unordered_map<cpp_int, cpp_int, hash_str<cpp_int>> data;

  data.insert(std::make_pair(z,x));
}

笔记:

  • 我不知道是否cpp_int::str()输出类型存储的完整精度,但如果不是,那么不同的值会产生相同的值str(),因此哈希将在哈希表的同一个桶中发生冲突,这不会破坏功能但会移开从 O(1) 到 O(N) 性能。因此,如果默认情况下str()不显示完整精度,但有一种方法可以强制它,那么如果您处理大量差异非常小的值,那将是一个好主意。

  • 与浮点类型作为键的所有用途一样,要小心,因为微小的舍入差异可能导致现有映射条目找不到/不匹配,从而导致意外的“重复”等。

如果您的程序太慢并且配置文件证明散列是原因,那么请担心替代方案或升级提升....

于 2015-08-19T04:19:35.380 回答