Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preallocate memory for vector of strings (C++ vector<string>)

In C++, is there a clever (i.e. fast) way to pre-allocate memory for a vector of strings so that each element has some minimum size? The naive way I have is as follows:

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

Many thanks in advance,

Adam

like image 826
Adam Avatar asked Aug 05 '26 17:08

Adam


2 Answers

There's no fast way to do it. You can get fewer lines of code, but you're still going to make one call to reserve for each std::string in the std::vector.

I believe EASTL or Boost.Pool may help, if you're willing to go that route.

like image 116
Max Lybbert Avatar answered Aug 07 '26 06:08

Max Lybbert


The only way to pre-allocate all of this memory at once is by implementing your own allocators, like so (code is not complete, as obviously allocators have more members that need to be supported):

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.

This is really only practical if you know exactly what you're allocating for the lifetime of these data structures, since more flexible allocation will require heap-management-like logic in your allocators.

like image 27
Jollymorphic Avatar answered Aug 07 '26 06:08

Jollymorphic