c ++中字符串向量消耗的内存

hel*_*lix 6 c++ memory vector

我正在用c ++创建一个字符串向量.我需要的是这个向量以字节为单位消耗的总内存.

因为字符串是可变大小的,所以现在我遍历每个向量元素并找到它的长度然后在最后我将它乘以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;
Run Code Online (Sandbox Code Playgroud)

或者,找到字符串数组的内存消耗的解决方案也可以.让我们说吧

string a[SIZE]
Run Code Online (Sandbox Code Playgroud)

找到一个字节数?

Tho*_*ews 4

粗略估计占用的内存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;
Run Code Online (Sandbox Code Playgroud)

由于vectorstring不是固定大小的对象,因此动态内存分配可能会占用一些额外的开销。这就是为什么这是一个估计。

编辑1:
以上计算假设单个字符单位;不是多字节字符。

  • 您还想使用“capacity”而不是“size()”。“size()”反映实际使用的内存量,而“capacity()”反映实际分配的内存量。 (2认同)