通过将 boost::pool_allocator 作为参数传递来创建 std::vector

Create std::vector by passing boost::pool_allocator as argument

我有一段代码会在循环中 运行 并在每次迭代时创建 std::vector,所以我想使用 Boost 的 pool_allocator 来提高效率。但是,我正在使用的库不允许我将分配器作为模板参数传递:

  std::vector<int, boost::pool_allocator<int> > v;

  // This doesn't work because the library doesn't support the new type with the custom allocator
  library::processVector(v);

所以我想将分配器作为参数传入以绕过它:

auto pool{boost::pool_allocator<int>()};
std::vector<int> v(pool);

但这给了我一个编译错误:

error: no matching function for call to ‘std::vector<int>::vector(int, boost::pool_allocator<int>&)’

我该如何解决这个问题?

恐怕你做不到。用于标准容器的分配器必须作为模板参数传递。如果您确实提供了不同的分配器类型作为模板参数,则传递给容器构造函数的分配器参数的类型必须完全匹配或隐式转换为分配器模板参数,因此它应该是:

 typedef boost::pool_allocator<int> pool;
 std::vector<int, pool> v(pool);

您真的需要在每次迭代时都创建一个向量吗?

通常,您在循环外创建向量,并在每次迭代时 .clear() 创建它。这可以重用已分配的内存。

当然,这并不适用于所有情况。例如,如果该库通过 std::move().swap() 将其分配给另一个库而从 vector 移出,这将无济于事。