C++ STL map, rbegin() program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
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:
To do: Using the C++ rbegin() to return an iterator addressing the first element in a reversed map in C++ programming
To show: How to use the C++ map, rbegin() to return an iterator addressing the first element in a reversed map in C++ programming
// C++ STL map, rbegin()
#include <map>
#include <iostream>
using namespace std;
int main(void)
{
// map container
map <int, int> m1;
// map iterators
map <int, int> :: iterator m1_Iter;
map <int, int> :: reverse_iterator m1_rIter;
map <int, int> :: const_reverse_iterator m1_crIter;
// simplify pair<int, int> to Int_Pair
typedef pair <int, int> Int_Pair;
// insert data into the map
m1.insert(Int_Pair(1, 10));
m1.insert(Int_Pair(2, 20));
m1.insert(Int_Pair(3, 9));
m1.insert(Int_Pair(4, 30));
// iterate and print
m1_rIter = m1.rbegin();
cout<<"The first element of the reversed map m1 is "<<m1_rIter->first<<endl;
// begin() can be used to start an iteration through a map in a forward order
cout<<"The map is: ";
for (m1_Iter = m1.begin(); m1_Iter != m1.end(); m1_Iter++)
cout<<m1_Iter->first<<" ";
cout<<endl;
// rbegin() can be used to start an iteration through a map in a reverse order
cout<<"The reversed map is: ";
for (m1_rIter = m1.rbegin(); m1_rIter != m1.rend(); m1_rIter++)
cout<<m1_rIter->first<<" ";
cout<<endl;
// a map element can be erased by dereferencing to its key
m1_rIter = m1.rbegin( );
m1.erase(m1_rIter->first);
m1_rIter = m1.rbegin();
cout<<"After the erase(), the first element in the reversed map is "<<m1_rIter->first<<"."<<endl;
return 0;
}
Output examples:
The first element of the reversed map m1 is 4
The map is: 1 2 3 4
The reversed map is: 4 3 2 1
After the erase(), the first element in the reversed map is 3.
Press any key to continue . . .