问题
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.
回答1:
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);
回答2:
You can also use reserve for strings. I'm not that experienced with vectors but you could make a custom class that allocates a certain numbers of characters for a string field and make of vector of that class instead.
回答3:
I would create a custom allocator which would return an extra 10 bytes whenever asked - to ensure that only 1 allocation is done / string. But I have to say this sounds a lot like premature optimisation.
来源:https://stackoverflow.com/questions/47571506/reserve-function-for-vector-of-strings-in-c