Difference between “size” and “capacity” in C++ in String

In this post, we are going to investigate the difference between the size and capacity of strings in C++.

The difference between the size and capacity of a string in C++ is pretty obvious. The size of a string is the number of letters present in the string whereas the capacity is the amount of memory it holds or rather the amount of memory it has reserved for the string so that when we insert more items in the string it will not need to reallocate more memory. This is the maximum memory allocated for one string. This can vary with various algorithms. Such as some might allocate the N+1 amount of memory for N elements while some might allocate 2*N amount of elements. Upon filling up that space it will reallocate another 2*N space. This is pretty space-wasting but this provides more security and stability to the system.

So let us see how to write a program that can show us the difference between the size and capacity of a string. To find the size and capacity we will have to use the (.size) and (.capacity) function.

Algorithm to show the difference between “capacity” and “size” of a string:

  1. Declare a variable of the string class.
  2. Enter a string and store it in the string variable.
  3. Print the size by using string.size (Find size of string without using library functions in C++ )
  4. Print the capacity by using string.capacity
  5. End

 

Program to demonstrate size vs capacity in C++

#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string newstring;
    newstring=("Hello                 ");
    cout << newstring << endl;
    cout << "Size = " << newstring.size() << endl;
    cout << "Capacity = "<< newstring.capacity() << endl;
    newstring.append("World");                                      //this attaches the string to the previous string
    cout << newstring<< endl;
    cout << "Size = " << newstring.size() << endl;
    cout << "Capacity = "<< newstring.capacity() << endl;
    return 0;
}

Output of the following code:

Difference between "size" and "capacity" in C++ in String

Leave a Reply

Your email address will not be published. Required fields are marked *