std::basic_string<CharT,Traits,Allocator>:: capacity
From cppreference.net
<
cpp
|
string
|
basic string
C++
Strings library
| Classes | ||||
|
(C++17)
|
||||
std::basic_string
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
size_type capacity
(
(
)
const
;
|
(自 C++11 起为 noexcept)
(自 C++20 起为 constexpr) |
|
返回字符串当前已分配空间的字符数量。
目录 |
参数
(无)
返回值
当前已分配存储的容量,即可用于存储元素的可用空间。
复杂度
常量。
注释
从分配器获取但无法用于存储任何元素的内存位置不计入已分配存储空间。注意空终止符不是 std::basic_string 的元素。
示例
运行此代码
#include <iomanip> #include <iostream> #include <string> void show_capacity(std::string const& s) { std::cout << std::quoted(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); std::cout << "\nDemonstrate the capacity's growth policy." "\nSize: Capacity: Ratio:\n" << std::left; std::string g; auto old_cap{g.capacity()}; for (int mark{}; mark != 5; ++mark) { while (old_cap == g.capacity()) g.push_back('.'); std::cout << std::setw( 7) << g.size() << std::setw(11) << g.capacity() << std::setw(10) << g.capacity() / static_cast<float>(old_cap) << '\n'; old_cap = g.capacity(); } }
可能的输出:
"Exemplar" has capacity 15. "Exemplar is an example string." has capacity 30. "" has capacity 30. Demonstrate the capacity's growth policy. Size: Capacity: Ratio: 16 30 2 31 60 2 61 120 2 121 240 2 241 480 2
参见
|
返回字符数量
(公开成员函数) |
|
|
预留存储空间
(公开成员函数) |