Click here to Skip to main content
15,887,945 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here is a code :

C++
#include <iostream>
#include <string>
using namespace std;
int main() {
    std::string s1 = "Hello";
    cout << ".size() returns " << s1.size() << endl;
    cout << ".capacity() returns " << s1.capacity() << endl;
    s1.append("!");
    cout << ".size() returns " << s1.size() << endl;
    cout << ".capacity() returns " << s1.capacity() << endl;
    return 0;
}

This is an Output :

sometimes Size=6 and Capacity=12....
Why Its different?

What is different between Capacity and Size?

Thanks in advance.
Posted
Updated 29-Nov-10 10:35am
v3

Capacity is how many characters the string can hold, and size is the actual size of the string as it exists.
 
Share this answer
 
Comments
LetsTalk 29-Nov-10 9:30am    
so how buffer know the size of capacity? how it calculate it since i didnt declear anythings?!
Capacity is calculated when the string is created or resized, based on its current content. This allows a small increase in the string's contents without the necessity of allocating a new memory block. The actual value used is internal to the class.
 
Share this answer
 
All STL containers allocate memory dynamically based on demand.
But the memory allocated is always greater than what is actually required so that it cope with future additions to the container without allocating additional memory.

This is done because memory allocation is time consuming.
Also too much memory allocation will unnecessarily waste memory.

So there is a balance between the 2.

So size returns the actual size of the contents of the container and capacity returns the total memory currently allocated.

Try this -
std::string s1;
for (int i = 0; i < 100; ++i)
{
    s1.append("");
    cout << "Size = " << s1.size() << ", Capacity = " << s1.capacity() << endl;
}
 
Share this answer
 
Comments
Dalek Dave 29-Nov-10 17:43pm    
Good Answer
Rajesh Anuhya 30-Nov-10 9:14am    
Good call Superman

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900