C++STD无序集/映射与Boost无序集/贴图



它们之间有什么区别,何时应该使用它们?

我在一台旧笔记本电脑上进行了一些测试,在存储int和long等基本类型时,似乎没有显著的性能差异。我认为主要的区别之一是boost容器模板方法不支持std::piecewise_struct和元组,这会导致额外的开销。

编辑:我正在做的东西已经有了很多boost功能,所以我不担心boost库的兼容性问题。

Boost有一些标准库中不存在的功能。我脑海中浮现:

  • Boost Hash,它比专门化std::hash<>更灵活、更容易定制(尽管也支持专门化boost::hash<>;更简单的途径是实现inline friend size_t hash_value(T const&),它将"神奇地"被默认的hash<>实现"拾取">

  • Boost倾向于更好地支持异构查找(查找扩展的查找/插入签名(

  • 有序版本可能具有额外的构造器来有效地构建已知有序序列

  • 一般来说,Boost容器(包括Boost容器库中的其他容器(有更多的保证/选项:

    • (更好(支持有状态分配器(包括scoped_allocater_aptor,因此完全支持uses_allocator/allocator_arg_t(
    • 构造函数不分配
    • 对模板参数中不完整类型的一些支持
  • 据我所知,分段构造在Boost中是非常好的。例如,1.48.0的更改注释列表:

    * `emplace` used to emulate the variadic pair constructors that
    appeared in early C++0x drafts. Since they were removed it no
    longer does so. It does emulate the new `piecewise_construct`
    pair constructors - only you need to use
    `boost::piecewise_construct`. To use the old emulation of
    the variadic constructors define
    

摘要

我预计在表现上不会有显著差异。

执行质量将存在差异。Boost的编译速度可能会慢一点,并且支持旧的编译器版本。

奖金

作为对评论的回应,这里有一个示例,概述了上面提到的一些功能,特别是分段定位的使用:

实时编译器资源管理器

#include <boost/unordered_map.hpp>
#include <iomanip>
#include <fmt/ranges.h>
#include <fmt/ostream.h>
struct MyKey {
MyKey(int i, std::string s) : _i(i), _s(std::move(s)) {}
bool operator==(MyKey const&) const = default;
private:
int _i;
std::string _s;
friend size_t hash_value(MyKey const& mk) {
using boost::hash_value;
size_t seed = hash_value(mk._i);
boost::hash_combine(seed, hash_value(mk._s));
return seed;
}
friend auto& operator<<(auto& os, MyKey const& mk) {
return os << "[" << mk._i << ", " << std::quoted(mk._s) << "]";
}
};
int main() {
boost::unordered_map<MyKey, std::string> m;
m.emplace(boost::unordered::piecewise_construct,
boost::make_tuple(42, "forty-two"),
boost::make_tuple("the answer"));
m.emplace(std::piecewise_construct,
std::/*make_*/tuple(43, "forty-three"),
std::/*make_*/tuple("not the answer"));
fmt::print("m: {}n", m);
}

打印

m: {([43, "forty-three"], "not the answer"), ([42, "forty-two"], "the answer")}

最新更新