The C++ push_back() 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: Adds an element to the end of the string using push_back() function in C++ programming

To show: How to use the push_back() function to add an element to the end of the string in C++ programming

 

// the push_back() C++ example

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

string str1("Testing the push_back()");

basic_string <char>::iterator StrIter, Str1Iter;

 

cout<<"str1 string is: ";

for(StrIter = str1.begin(); StrIter != str1.end(); StrIter++)

cout<<*StrIter;

cout<<endl;

 

cout<<"Move the pointer to the end of string..."<<endl;

Str1Iter = str1.end();

 

cout<<"Then add an element to the end of the string..."<<endl;

str1.push_back('T');

cout<<"\nOperation: str1.end() then str1.push_back('T')"<<endl;

cout<<"The last character of str1 string is: "

<<*Str1Iter;

 

cout<<endl;

cout<<"\nMove the pointer from the beginning to the end..."<<endl;

cout<<"Now, str1 string is: ";

for(StrIter = str1.begin(); StrIter != str1.end(); StrIter++)

cout<<*StrIter;

cout<<endl;

 

return 0;

}

 

Output example:

 

str1 string is: Testing the push_back()

Move the pointer to the end of string...

Then add an element to the end of the string...

 

Operation: str1.end() then str1.push_back('T')

The last character of str1 string is: T

 

Move the pointer from the beginning to the end...

Now, str1 string is: Testing the push_back()T

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index