此函数减少了字符串的容量,并使其等于其大小。
考虑一个字符串str。语法为:
str.shrink_to_fit();
它不返回任何值。
让我们看一个简单的例子。
#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()函数应用于字符串,以使字符串的容量等于字符串的大小。
让我们看另一个简单的例子。
链接: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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)