Size versus Capacity

We'll test and alter the capacity of a string.

The number of elements a string has (str.size()) is in general smaller than the number of elements, for which space is reserved: str.capacity(). Therefore, if you add elements to a string, new memory may not be allocated automatically. std:max_size() returns the maximum number of elements a string can have. For the three methods the following relation holds: str.size() <= str.capacity() <= str.max_size().

The following table shows the methods for dealing with the memory management of the string.

Methods Description
str.empty() Checks if str has elements.
str.size(), str.length() Number of elements of the str.
str.capacity() Number of elements str can have without reallocation.
str.max_size() Number of elements str can maximal have.
str.resize(n) Increases str to n elements.
str.reserve(n) Reserve memory for a least n elements.
str.shrink_to_fit() Adjusts the capacity of the string to it’s size.

The request str.shrink_to_fit() is as in the case of std::vector non-binding.

Get hands-on with 1200+ tech skills courses.