首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::basic_string::shrink_to_fit

void shrink_to_fit();

(since C++11)

请求清除未使用的容量。

这是一个不具有约束力的请求来减少capacity()size().这取决于请求是否得到满足的实现。

如果发生重新分配,则所有指针、引用和迭代器都将失效。

参数

%280%29

返回值

%280%29

复杂性

常量。

二次

代码语言:javascript
复制
#include <iostream>
#include <string>
 
int main()
{
    std::string s;
    std::cout << "Default-constructed capacity is " << s.capacity() << '\n';
    s.resize(100);
    std::cout << "Capacity of a 100-element string is " << s.capacity() << '\n';
    s.clear();
    std::cout << "Capacity after clear() is " << s.capacity() << '\n';
    s.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << s.capacity() << '\n';
}

二次

产出:

二次

代码语言:javascript
复制
Default-constructed capacity is 0
Capacity of a 100-element string is 100
Capacity after clear() is 100
Capacity after shrink_to_fit() is 0

二次

另见

sizelength

returns the number of characters (public member function)

capacity

returns the number of characters that can be held in currently allocated storage (public member function)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券