map::rbegin , map::cbegin and map::crbegin function


In this post we will discuss three member functions of the map container

1 rbegin()
2 cbegin()
3 crbegin()

The detail discussion of each of these functions is provided below.



reverse_iterator rbegin();

The map::rbegin function returns the reverse_iterator of the map container.

Parameters:
none

Return type
reverse_iterator -Returns read and write reverse_iterator pointing to the last element in the container.

Note the reverser_iterator will start pointing to the last element so the iteration is done in descending order.This simply means the key decreases as the iterator move forward.

map<double,char> m{{2.32 , ‘3’} , {2.56 , ‘7’} , {1.23 , ‘9’}};

map<double,char>::reverse_iterator mRit=m.rbegin( );

cout<< mRit->first << ” ” << mRit->second << endl ;

++mRit;

cout<< mRit->first << ” ” << mRit->second << endl ;

Output

2.56 7
2.32 3

Here is another program which shows the write permissibly using the returned iterator.

map<double,char> m{{2.32 , ‘3’} , {2.56 , ‘7’} , {1.23 , ‘9’}};

map<double,char>::reverse_iterator mRit=m.rbegin( );

mRit->second =’*’ ;

cout<< mRit->first << ” ” << mRit->second << endl ;

Output

2.56 *


 


Stop wasting time,earn money($$$) from your website-Join Now!


const_iterator cbegin( ) const noexcept;

The map::cbegin function returns a constant iterator to the container.

Parameters:
none

Return type
const_iterator -A read only iterator of the container pointing to the first element.

The iteration is done in normal order.Since the returned iterator is read only unfortunately it can be only used for reading elements form the container.

Code example

map<char,string> mC{{‘C’ , “Chameleon”} , {‘A’ , “Above”} , {‘N’ , “Numerology”}};

map<char,string>::const_iterator it=mC.cbegin() ;

cout<< it->first << ” ” << it->second << endl ;

it->second=”New” ; //error,const_iterator type

Output

A Above






const_reverse_iterator crbegin() const noexcept;

The map:crbegin does what rbegin() and cbegin() does.

Parameters:
none

Return type
const_reverse_iterator -An iterator which is a const type and has a reverse iteration.

Note the returned iterator access element starting from last element of the container.

Code example

map<int,string> mC{{12 , “12 O’clock”} , {3 , “A3 am”} , {11 , “11pm”}};

map<char,string>::const_iterator it1=mC.crbegin() ;

cout<< it1->first << ” ” << it1->second << endl ;

it1->second=”New” ; //error,const_reverse_iterator type

Output

12 O’çlock