std::basic_string<CharT,Traits,Allocator>::capacity
從 cppreference.com
< cpp | string | basic string
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
[編輯] 參閱
返回字符數 (公開成員函數) | |
預留存儲 (公開成員函數) |