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

泄露秘密 提交于 2019-12-07 11:45:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!