跳到主要内容

std::string capacity() 方法

// Const version only
constexpr size_type capacity() const noexcept;

返回字符串当前已分配空间的字符数。

参数

(无)

返回值

当前已分配存储的容量。

复杂度

常数 - O(1)

异常

(无)

备注

从分配器获取但不可用于存储任何元素的内存位置不计入已分配存储。

注意

空终止符不是 std::basic_string 的元素。

示例

Main.cpp
#include <iostream>
#include <iomanip>
#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
本文源自 此 CppReference 页面。它可能为了改进或编辑偏好而被修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::string capacity() 方法

// Const version only
constexpr size_type capacity() const noexcept;

返回字符串当前已分配空间的字符数。

参数

(无)

返回值

当前已分配存储的容量。

复杂度

常数 - O(1)

异常

(无)

备注

从分配器获取但不可用于存储任何元素的内存位置不计入已分配存储。

注意

空终止符不是 std::basic_string 的元素。

示例

Main.cpp
#include <iostream>
#include <iomanip>
#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
本文源自 此 CppReference 页面。它可能为了改进或编辑偏好而被修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。