std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++
String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let’s see a few of the functionalities string class provides.
Header File <string>
There are many functionalities associated with string class but we will be focusing on only three of them, these are:
- std :: string :: length
- std :: string :: size
- std :: string :: capacity
All three functions are public member functions of the Class String. To know more about other functionalities in string class refer to a String in STL.
Returns the length of a string. This returns the exact no. of characters or bytes used and not the memory that is allocated at the backend. length member function never throws exceptions.
size_t std::string::length( )
- size_t is a typedef version of unsigned int, as sizes cannot be negative.
- No parameters are passed, the string is identified with this pointer.
Returns the length of the string, in terms of bytes. This returns the exact no. of characters or bytes used and not the memory that is allocated at the backend. Both length and size are the same and return the same value but size can be used in any container like vector, list, etc whereas length is more associated with the string. size member function never throws exceptions.
size_t std::string::size( )
- Returns the size of the storage space currently allocated in the Memory for that string object.
- This does NOT return the exact no. of characters or bytes used but, the memory that is allocated at the backend.
- Capacity is always GREATER THAN EQUAL TO size/length.
- The extra space allows the string object to optimize its operations when new characters are added.
- Capacity is NOT limited, as needed the capacity is increased by the compiler.
- Capacity does not Reduce automatically, it needs to be done explicitly.
size_t std::string::capacity( );
str is : size: 0 length: 0 capacity: 0 str is : H size: 1 length: 1 capacity: 1 str is : Hello size: 5 length: 5 capacity: 5 str is : Hello size: 6 length: 6 capacity: 10 str is : Hello GFG Reader size: 16 length: 16 capacity: 20 str is : Hello size: 5 length: 5 capacity: 20 str is : Hello size: 5 length: 5 capacity: 7 str is : Hello size: 5 length: 5 capacity: 35
The above code demonstrates all the possible scenarios. The facts have also proven that Capacity >= size/length, then the capacity increases automatically as the size of the string crosses the previous capacity, then the capacity is never reduced back when the size goes down, but that can be done explicitly by the programmer using reserve function.
Time and Space Complexity