为字符串向量预分配内存(C ++ vector <string>)</string>

时间:2011-04-04 19:37:42

标签: c++ stl memory-management

在C ++中,是否有一种聪明的(即快速)方法为字符串向量预分配内存,以便每个元素都有一些最小的大小?我天真的方式如下:

vector<string> my_string_vector;
my_string_vector.resize(1000);
for (unsigned int ui=0; ui<1000; ui++)
   my_string_vector[ui].reserve(1024);

非常感谢,

亚当

3 个答案:

答案 0 :(得分:3)

没有快速的方法可以做到这一点。您可以获得更少的代码行,但您仍然会为reserve中的每个std::string拨打一次std::vector

如果您愿意走这条路,我相信EASTLBoost.Pool可能会有所帮助。

答案 1 :(得分:1)

这将创建一个容量至少为1024的单个字符串,然后将其复制构造1000次到向量中。

#include <string>
#include <iostream>
#include <vector>

int main() {
   std::string s;
   s.reserve(1024);
   std::vector<std::string> my_string_vector(1000, s);
   std::cout << my_string_vector[42].capacity() << "\n";
}

答案 2 :(得分:1)

一次预先分配所有内存的唯一方法是实现自己的分配器,如下所示(代码不完整,显然分配器有更多需要支持的成员):

class my_string_allocator {
public:
   char * allocate(size_type n, allocator<void>::const_pointer hint=0) {
      // ... grab a chunk from your pre-allocated pool ...
   }
};

typedef basic_string<char, char_traits<char>, my_string_allocator> my_string;

class my_vector_allocator {
public:
   my_string * allocate(size_type n, allocator<void>::const_pointer hint=0) {
      // ... similar magic goes here ...
   }
}

vector<my_string, my_vector_allocator> my_string_vector(1000);
for (unsigned int ui=0; ui<1000; ui++)
   my_string_vector[ui].reserve(1024);  // Memory taken from pool; no allocation.

如果您确切知道在这些数据结构的生命周期中分配的内容,这实际上是切实可行的,因为更灵活的分配将需要分配器中类似堆管理的逻辑。

相关问题