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 we add elements to a string, new memory will not necessarily be allocated. std:max_size()
return the maximum amount 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 memory management of strings.
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) |
Reserves 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 1400+ tech skills courses.