我很难找到一个例子。我的代码如下所示:
typedef boost::unordered_set<CustomObject, boost::hash<CustomObject>,
CustomObjectEqual, allocator<CustomObject> > CustomObjectSet;
我尝试直接使用 fast_pool_allocator ,但这会导致编译错误(使用 std :: allocator 工作)。我的问题是:
答案 0 :(得分:2)
问题1:我是否需要为CustomObject创建自定义分配器?
没有。没有它就会编译。分配器使用默认参数。在下面的示例中,这些是相同的:
using fast_allocator = boost::fast_pool_allocator<
CustomObject,
boost::default_user_allocator_new_delete,
boost::mutex,
32,
0>;
using fast_allocator = boost::fast_pool_allocator<CustomObject>;
实施例
#include <boost/unordered_set.hpp>
#include <boost/pool/pool.hpp>
#include <boost/pool/pool_alloc.hpp>
struct CustomObject {
CustomObject(std::size_t value)
: value(value)
{
}
std::size_t value;
};
struct CustomObjectKeyEq {
bool operator()(CustomObject const& l, CustomObject const& r) const
{
return l.value == r.value;
}
};
std::size_t hash_value(CustomObject const& value)
{
return value.value;
}
int main()
{
typedef boost::unordered_set<CustomObject,
boost::hash<CustomObject>,
CustomObjectKeyEq> StandardObjectSet;
StandardObjectSet set1;
set1.insert(10);
set1.insert(20);
set1.insert(30);
using fast_allocator = boost::fast_pool_allocator<CustomObject>;
typedef boost::unordered_set<CustomObject,
boost::hash<CustomObject>,
CustomObjectKeyEq,
fast_allocator> CustomObjectSet;
CustomObjectSet set2;
set2.insert(10);
set2.insert(20);
set2.insert(30);
return 0;
}
问题2:这是否会提高我的计划速度?
通常,您必须对其进行测量。它对上面的例子没有重大影响。在set1中插入一百万个对象:
0.588423s wall,0.570000s user + 0.020000s system = 0.590000s CPU(100.3%)
并进入set2:
0.584661s wall,0.560000s user + 0.010000s system = 0.570000s CPU(97.5%) 1000000