std::basic_string<CharT,Traits,Allocator>::capacity
来自cppreference.com
<tbody>
</tbody>
size_type capacity() const; |
(C++11 起为 noexcept) (C++20 起为 constexpr) |
|
返回当前已为字符串分配空间的字符数。
参数
(无)
返回值
当前分配的存储,即可用于存储元素的存储的容量。
复杂度
常数。
注解
从分配器获得,但不可用于存储任何元素的内存位置不计入分配的存储。注意空终止符不是 basic_string 的元素。
示例
运行此代码
#include <iomanip>
#include <iostream>
#include <string>
void show_capacity(std::string const& s)
{
std::cout << std::quoted(s) << " 的容量为 " << 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 << "\n演示容量增长策略。"
"\n大小: 容量: 比率:\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( 7) << g.capacity()
<< std::setw(10) << g.capacity() / static_cast<float>(old_cap) << '\n';
old_cap = g.capacity();
}
}
可能的输出:
"Exemplar" 的容量为 15。
"Exemplar is an example string." 的容量为 30。
"" 的容量为 30。
演示容量增长策略。
大小: 容量: 比率:
16 30 2
31 60 2
61 120 2
121 240 2
241 480 2
参阅
| 返回字符数 (公开成员函数) | |
| 预留存储 (公开成员函数) |