进程 中的 void shrink_to_fit()函数

首页 / C++入门教程 / 进程 中的 void shrink_to_fit()函数

此函数减少了字符串的容量,并使其等于其大小。

shrink_to_fit - 语法

考虑一个字符串str。语法为:

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-string-shrink-to-fit-function.html

来源:LearnFk无涯教程网

str.shrink_to_fit();

shrink_to_fit - 返回值

它不返回任何值。

shrink_to_fit - 例子1

让我们看一个简单的例子。

#include<iostream>
using namespace std;
int main()
{
	string str="C++ Programming";
	cout<<str.capacity()<<'\n';
	str.shrink_to_fit();
	cout<<str.capacity();
	return 0;
}

输出:

15
15

在此示例中,将 shrink_to_fit()函数应用于字符串,以使字符串的容量等于字符串的大小。

shrink_to_fit - 例子2

让我们看另一个简单的例子。

#include<iostream>
using namespace std;
int main()
{
	string str="Computer is my favorite subject";
	cout<<"Initial string value is :"<<str<<'\n';
	str.resize(24);
	cout<<"After resizing,string value is :"<<str<<'\n';
	str.shrink_to_fit();
	cout<<"capacity of the string is :"<<str.capacity()<<'\n';
	cout<<"size of the string is  :"<<str.size();
            return 0;
}

输出:

Initial string value is: Computer is my favorite subject
After resizing, string value is: Computer is my favorite 
capacity of the string is :24
size of the string is  :24

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

朱赟的技术管理课 -〔朱赟〕

Java并发编程实战 -〔王宝令〕

消息队列高手课 -〔李玥〕

Redis核心技术与实战 -〔蒋德钧〕

用户体验设计实战课 -〔相辉〕

大厂晋升指南 -〔李运华〕

JavaScript进阶实战课 -〔石川〕

结构思考力 · 透过结构看问题解决 -〔李忠秋〕

LangChain 实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)