gpt4 book ai didi

c++ - 为什么我不能将 std::unordered_map 或 boost::unordered_map 与 boost::multiprecision 类型一起使用?

转载 作者:行者123 更新时间:2023-11-30 02:37:01 26 4
gpt4 key购买 nike

我正在尝试使用 boost::mulprecision 类型创建一个 STL(或 boost)unordered_map,例如cpp_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;
}

完整的错误日志是 here

第一个错误:

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);
^

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

编辑:

question of which this might be a duplicate使用在 boost 1.56 中添加的 boost::multiprecision 的序列化支持(至少根据文档 @1.55@1.56 中的差异。

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

最佳答案

您的“question of which this might be a duplicate”记录了问题本身的一种工作技术 - 散列字符串表示:

#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() 不显示完全精度,但有一种方法可以强制显示它,那么如果您处理许多差异非常小的值,那将是个好主意。

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

    <

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

关于c++ - 为什么我不能将 std::unordered_map 或 boost::unordered_map 与 boost::multiprecision 类型一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32082786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com