Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "size" and "capacity" in c++ string?

Tags:

c++

string

stl

I have this snippet from Thinking in C++.

#include <iostream>
#include <string>

int main ()
{
string bigNews("I saw Elvis in a UFO. ");
cout << bigNews << endl;
 bigNews.insert(0, " thought I ");
cout << bigNews << endl;
cout << "Size = " << bigNews.size() << endl;
cout << "Capacity = "
<< bigNews.capacity() << endl;
bigNews.append("I've been working too hard.");
cout << bigNews << endl;
cout << "Size = " << bigNews.size() << endl;
cout << "Capacity = "
<< bigNews.capacity() << endl;
  return 0;
}

And I get output as shown below:

I saw Elvis in a UFO. 
 thought I I saw Elvis in a UFO. 
Size = 33
Capacity = 44
 thought I I saw Elvis in a UFO. I've been working too hard.
Size = 60
Capacity = 88

I can figure out why the size increases, but I am not able to make out how the Capacity increases?

What i know is Capacity is the string buffer where we can Pushback, but how that space is allocated?

like image 586
zer0Id0l Avatar asked Sep 25 '13 04:09

zer0Id0l


People also ask

What is capacity of string in C?

The capacity of a string reflects how much memory the string allocated to hold its contents. This value is measured in string characters, excluding the NULL terminator. For example, a string with capacity 8 could hold 8 characters. size_type string::capacity() const.

What is the difference between string length and string size?

Using string::size: The method string::size returns the length of the string, in terms of bytes. Using string::length: The method string::length returns the length of the string, in terms of bytes. Both string::size and string::length are synonyms and return the exact same value.

What is the size of a string variable?

A variable-length string can contain up to approximately 2 billion (2^31) characters. A fixed-length string can contain 1 to approximately 64 K (2^16) characters.

How do I find the size of a string?

You can get the length of a string object by using a size() function or a length() function. The size() and length() functions are just synonyms and they both do exactly same thing.


1 Answers

capacity is the maximum number of characters that the string can currently hold without having to grow. size is how many characters actually exist in the string. The reason they're separate concepts is that allocating memory is generally inefficient, so you try to allocate as rarely as possible by grabbing more memory than you actually need at one time. (Many data structures use a "doubling" method where, if they hit their capacity of N and need more space, they will allocate 2*N space, to avoid having to reallocate again any time soon.)

capacity will increase automatically as you use the string and require more space. You can also manually increase it using the reserve function.

like image 98
Chris Hayes Avatar answered Oct 17 '22 04:10

Chris Hayes