进程 中的 void shrink_to_fit()函数

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

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

shrink_to_fit - 语法

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

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

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

无涯教程网

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

来源:LearnFk无涯教程网

#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并发编程实战 -〔王宝令〕

零基础学Java -〔臧萌〕

研发效率破局之道 -〔葛俊〕

职场求生攻略 -〔臧萌〕

Django快速开发实战 -〔吕召刚〕

郭东白的架构课 -〔郭东白〕

Dubbo源码剖析与实战 -〔何辉〕

工程师个人发展指南 -〔李云〕

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