C ++中用于字符串向量的reserve()函数 [英] 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
我的向量不需要超过1024个插槽,每个字符串将需要10个字符空间。
我已经为向量保留了1024个内存插槽。
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?
谢谢。
推荐答案
我的向量不需要超过1024个插槽,并且每个字符串将需要10个字符空格。
然后,考虑以下 MyString $ c的(部分)定义$ c>类:
#include <array>
#include <string>
class MyString {
std::array<std::string::value_type, 10> str;
public:
// ...
};
通过使用 MyString
而不是 std :: string
,当在 std :: vector
上调用 reserve
时, MyString
中包含的字符串所需的内存(即: str
,这是 std :: array
)将被分配:
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);
这篇关于C ++中用于字符串向量的reserve()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!