Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reserve() function for Vector Of Strings in C++

I am trying to populate a vector of string type and the memory for the strings will be updated periodically.I found out in a forum that, both of these processes consume a lot of time due to memory reallocation every time I update the size and I also read that the reserve function solves the problem pretty much for both the cases. -> String & vector

My vector wont need more than 1024 slots and each string will need 10 character spaces. I have reserved 1024 memory slots for my vector.

vector<string> power_set;
power_set.reserve(1024);

But is there any way to reserve the memory-slots for the strings that are inside the vector slots as well?

Thanks In Advance.

like image 317
Akib Sadmanee Avatar asked Jan 31 '26 21:01

Akib Sadmanee


1 Answers

My vector wont need more than 1024 slots and each string will need 10 character spaces.

Then, consider the following (partial) definition of MyString class:

#include <array>
#include <string>   

class MyString {
    std::array<std::string::value_type, 10> str;

public:
// ...
};

By using MyString instead of std::string, when calling reserve on std::vector, the memory needed for the string contained in MyString (i.e.: str, which is a std::array) will be allocated:

vector<MyString> power_set;
power_set.reserve(1024);
like image 180
ネロク・ゴ Avatar answered Feb 02 '26 12:02

ネロク・ゴ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!