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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With