The C++ basic_string class member, reserve() program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the reverse(), basic_string class member to set the capacity of the string to a number at least as great as a specified number in C++ programming
To show: How to set the capacity of the string to a number at least as great as a specified number in C++ programming using reserve(), the basic_string class member in C++ programming
// the C++ reserve() example
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
string str1("Testing the reserve()");
cout<<"str1 string is: "<<str1<<endl;
basic_string <char>::size_type SizeStr1, Size1Str1;
SizeStr1 = str1.size();
basic_string <char>::size_type CapaStr1, Capa1Str1;
CapaStr1 = str1.capacity();
// compare size and capacity of the original string
cout<<"The size of str1 string is: "<<SizeStr1<<endl;
cout<<"The capacity of str1 string is: "<<CapaStr1<<endl<<endl;
// compare size and capacity of the string with added capacity
cout<<"Operation: str1.reserve(20)"<<endl;
str1.reserve(20);
Size1Str1 = str1.size();
Capa1Str1 = str1.capacity();
cout<<"str1 with increased capacity is: "<<str1<<endl;
cout<<"The size of str1 string is: "<<Size1Str1<<endl;
cout<<"The increased capacity of str1 string is: "<<Capa1Str1<<endl<<endl;
// compare size and capacity of the string with downsized capacity. Without any parameter,
// it should shrink to fit the number of the characters currently in the string
cout<<"Operation: str1.reserve()"<<endl;
str1.reserve();
basic_string <char>::size_type Size2Str1;
basic_string <char>::size_type Capa2Str1;
Size2Str1 = str1.size();
Capa2Str1 = str1.capacity();
cout<<"str1 with downsized capacity is: "<<str1<<endl;
cout<<"The size of str1 string is: "<<Size2Str1<<endl;
cout<<"The reduced capacity of str1 string is: "<<Capa2Str1<<endl;
return 0;
}
Output example:
str1 string is: Testing the reserve()
The size of str1 string is: 21
The capacity of str1 string is: 31
Operation: str1.reserve(20)
str1 with increased capacity is: Testing the reserve()
The size of str1 string is: 21
The increased capacity of str1 string is: 31
Operation: str1.reserve()
str1 with downsized capacity is: Testing the reserve()
The size of str1 string is: 21
The reduced capacity of str1 string is: 31
Press any key to continue . . .