Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory consumed by a string vector in c++

Tags:

c++

memory

vector

i am creating a vector of strings in c++. What i need is total memory consumed in bytes by this vector.

Since the strings are of variable size, right now i am iterating through every vector element and finding its length then at the end i am multiplying this to size of char. What I need is a cleaner solution.

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;

alternatively a solution to find the memory consumption of a string array would also do. let's say

string a[SIZE]

find number of bytes for a?

like image 624
helix Avatar asked Apr 25 '15 17:04

helix


1 Answers

A rough estimate of the memory occupied by 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;

Since the vector and string are not fixed sized objects, there may be some additional overhead occupied by the dynamic memory allocations. That is why this is an estimate.

Edit 1:
The above calculation assumes single character unit; not multibyte characters.

like image 122
Thomas Matthews Avatar answered Sep 27 '22 19:09

Thomas Matthews