我正在用 C++ 创建一个字符串 vector 。我需要的是此 vector 消耗的总内存(以字节为单位)。
由于字符串的大小可变,现在我遍历每个 vector 元素并找到它的长度,然后在最后我将它乘以 char 的大小。我需要的是更清洁的解决方案。
vector<string> v;
//insertion of elements
int len=0;
for(int i=0;i<v.size();i++)
len+=v[i].length();
int memory=sizeof(char)*len;
或者,找到字符串数组的内存消耗的解决方案也可以。让我们说
string a[SIZE]
找到a的字节数?
最佳答案
粗略估计std::vector<string>
占用的内存:
sizeof(std::vector<string>) // The size of the vector basics.
+ sizeof(std::string) * vector::size() // Size of the string object, not the text
// One string object for each item in the vector.
// **The multiplier may want to be the capacity of the vector,
// **the reserved quantity.
+ sum of each string's length;
自 vector
和 string
不是固定大小的对象,动态内存分配可能会占用一些额外的开销。这就是为什么这是一个估计。
编辑 1:
以上计算均采用单字符单位;不是多字节字符。
关于c++ - C++中的字符串 vector 消耗的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29868622/