C++ 字符串 shrink_to_fit()函数

C++ 字符串 shrink_to_fit()函数

这个函数会减小字符串的容量,使其等于其大小。

语法

假设有一个字符串 str。语法如下:

str.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()函数被应用于字符串,使得字符串的容量变为与字符串的大小相等。

示例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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程