名稱空間
變體
操作

std::basic_string<CharT,Traits,Allocator>::capacity

來自 cppreference.com
< cpp‎ | string‎ | basic_string
 
 
 
std::basic_string
 
size_type capacity() const;
(C++11 起無異常丟擲)
(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

[編輯] 參閱

返回字元數
(公共成員函式) [編輯]
預留儲存空間
(公共成員函式) [編輯]