Difference between revisions of "cpp/string/basic string/capacity"
From cppreference.com
< cpp | string | basic string
m (Undo revision 124704 by 79.156.56.92 (talk) recovery #2) |
m (Expand example to show capacity does not need to be equal to number of chars in string) |
||
Line 42: | Line 42: | ||
s += " is an example string."; | s += " is an example string."; | ||
+ | show_capacity(s); | ||
+ | |||
+ | s.clear(); | ||
show_capacity(s); | show_capacity(s); | ||
} | } | ||
Line 48: | Line 51: | ||
'Exemplar' has capacity 15. | 'Exemplar' has capacity 15. | ||
'Exemplar is an example string.' has capacity 30. | 'Exemplar is an example string.' has capacity 30. | ||
+ | '' has capacity 30. | ||
}} | }} | ||
===See also=== | ===See also=== |
Revision as of 14:49, 18 January 2022
size_type capacity() const; |
(until C++11) | |
size_type capacity() const noexcept; |
(since C++11) (until C++20) |
|
constexpr size_type capacity() const noexcept; |
(since C++20) | |
Returns the number of characters that the string has currently allocated space for.
Contents |
Parameters
(none)
Return value
Capacity of the currently allocated storage, i.e. the storage available for storing elements.
Complexity
Constant
Notes
Memory locations obtained from the allocator but not available for storing any element are not counted in the allocated storage. Note that the null terminator is not an element of the basic_string
.
Example
Run this code
#include <iostream> #include <string> void show_capacity(std::string const& s) { std::cout << "'" << s << "' has capacity " << s.capacity() << ".\n"; } int main() { std::string s{"Exemplar"}; show_capacity(s); s += " is an example string."; show_capacity(s); s.clear(); show_capacity(s); }
Possible output:
'Exemplar' has capacity 15. 'Exemplar is an example string.' has capacity 30. '' has capacity 30.
See also
returns the number of characters (public member function) | |
reserves storage (public member function) |