C ++中的字符串向量消耗的内存
memory consumed by a string vector in c++
我正在用 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;
或者找到字符串数组的内存消耗的解决方案也可以。假设
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++ 创建一个字符串向量。我需要的是此向量消耗的总内存(以字节为单位)。
由于字符串的大小可变,现在我遍历每个向量元素并找到它的长度,然后在最后我将它乘以 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:
以上计算均采用单字符单位;不是多字节字符。