std::basic_string<CharT,Traits,Allocator>::capacity
来自 cppreference.cn
< cpp | string | basic string
size_type capacity() const; |
(noexcept since C++11) (constexpr since C++20) |
|
返回字符串当前已分配空间的字符数。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
当前已分配存储的容量,即用于存储元素的可用存储空间。
[编辑] 复杂度
常数。
[编辑] 注意
从分配器获取但不可用于存储任何元素的内存位置不计入已分配的存储空间。请注意,空终止符不是 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
[编辑] 参见
返回字符数 (公共成员函数) | |
预留存储空间 (公共成员函数) |