std::basic_string<CharT,Traits,Allocator>::capacity
From cppreference.com
< cpp | string | 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
[編集] 関連項目
| 文字数を返す (public member function) | |
| ストレージを予約する (public member function) |