The C++ rbegin() and rend() 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 C++ rbegin() function to return an iterator to the first element in a reversed string and rend() to return an iterator that points just beyond the last element in a reversed string in C++ programming

To show: How to use the rbegin() and rend() in C++ programming to return an iterator to the first element in a reversed string and to return an iterator that points just beyond the last element in a reversed string respectively

 

// the C++ rbegin() and rend() example

#include <string>

#include <iostream>

using namespace std;

int main(void)

{

string str1("The reverse begin, rbegin()"), str2;

basic_string <char>::reverse_iterator StrIter, Str1Iter;

basic_string <char>::const_reverse_iterator str1_rcIter;

 

// well, no need to minus the null character huh?

cout<<"Operation: str1.rbegin()"<<endl;

Str1Iter = str1.rbegin();

cout<<"The first character of the reversed str1 string is: "

<<*Str1Iter<<endl;

cout<<"The full reversed str1 string is: ";

 

// rbegin() should be with rend()

for(StrIter = str1.rbegin(); StrIter != str1.rend(); StrIter++)

cout<<*StrIter;

cout<<"\n\n";

 

// the dereferenced iterator can be used to modify a character

cout<<"Operation: *Str1Iter = 'Z'"<<endl;

*Str1Iter = 'Z';

cout<<"The first character of the new str1 is: "

<<*Str1Iter<<endl;

cout<<"The full new reversed str1 is: ";

for(StrIter = str1.rbegin(); StrIter != str1.rend(); StrIter++)

cout<<*StrIter;

cout<<"\n\n";

 

// the following line will generate error because iterator is const

// *str1_rcIter = 'T';

//

// for an empty string, rbegin() is equivalent to rend()

cout<<"Operation: str2.rbegin() == str2.rend()"<<endl;

if(str2.rbegin() == str2.rend())

cout<<"The string str2 is empty."<<endl;

else

cout<<"The stringstr2 is not empty."<<endl;

return 0;

}

 

Output example:

 

Operation: str1.rbegin()

The first character of the reversed str1 string is: )

The full reversed str1 string is: )(nigebr ,nigeb esrever ehT

 

Operation: *Str1Iter = 'Z'

The first character of the new str1 is: Z

The full new reversed str1 is: Z(nigebr ,nigeb esrever ehT

 

Operation: str2.rbegin() == str2.rend()

The string str2 is empty.

Press any key to continue . . .

 

 

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