C++ STL deque, rbegin() code 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() to return an iterator to the first element in a reversed deque in C++ programming

To show: How to use the C++ deque, rbegin() to return an iterator to the first element in a reversed deque in C++ programming

 

// C++ STL deque, rbegin()

#include <deque>

#include <iostream>

using namespace std;

 

int main(void)

{

// deque container

deque <int> con1;

// deque iterator and reverse iterator

deque <int>::iterator con1_Iter;

deque <int>::reverse_iterator con1_rIter;

 

// If the following line had replaced the line above, an error would have resulted in the line modifying an element

// (commented below) because the iterator would have been const

// deque <int>::const_reverse_iterator con1_rIter;

//

con1.push_back(10);

con1.push_back(20);

con1.push_back(30);

con1.push_back(40);

con1.push_back(50);

con1.push_back(60);

 

// print the data and do some operations

cout<<"The con1 deque contains the elements: ";

for (con1_Iter = con1.begin(); con1_Iter != con1.end(); con1_Iter++)

cout<<*con1_Iter<<" ";

cout<<"in that order."<<endl;

con1_rIter = con1.rbegin();

cout<<"Last element in the con1 deque is "<<*con1_rIter<<"."<<endl;

// rbegin() can be used to iterate through a deque in reverse order

cout<<"The reversed con1 deque is: ";

for (con1_rIter = con1.rbegin(); con1_rIter != con1.rend(); con1_rIter++)

cout<<*con1_rIter<<" ";

cout<<endl;

con1_rIter = con1.rbegin();

// this would have caused an error if a const_reverse iterator had been declared as noted above

cout<<"Last element in con1 deque is "<<*con1_rIter<<"?"<<endl;

*con1_rIter = 70;

cout<<"After *con1_rIter = 70, last element in con1 deque is "<<*con1_rIter<<"?"<<endl;

return 0;

}

 

Output examples:

 

The con1 deque contains the elements: 10 20 30 40 50 60 in that order.

Last element in the con1 deque is 60.

The reversed con1 deque is: 60 50 40 30 20 10

Last element in con1 deque is 60?

After *con1_rIter = 70, last element in con1 deque is 70?

Press any key to continue . . .

 

 

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