map::rend,map::cend and map::crend function


In this post we will explore some of the ways to use the member functions of map container provided below:

1 rend
2 cend
3 crend

The function cend() and crend() are included with C++11 features.



reverse_iterator rend()

The rend returns a reverse iterator pointing to the memory before the first element in the container.

Parameters:
none

Return type
reverse_iterator -A reverse iterator that points to the one before the first pair element in the map container.

The element is access in the descending order of the key .

map rend

Code example

map<char,string>mp {{‘S’ , “Secular”} ,
{‘N’ , “Nomination”} ,
{‘T’ , “Taxation”} ,
{‘M’ , “Minority”} };

map<char,string>::reverse_iterator mri=mp.rend();

++mri;

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

++mri;

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

Output

T Taxation
S Secular


 


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


const_iterator cend( );

The cend returns an iterator that points to one past the last element in the container.

Parameters:
none

Return type
const_iterator-A read only iterator that points to one past the last element in the container.

The iteration is done in ascending order.

map cend

Code example

map<int,char> mp{{23 ,’$’} , {67 , ‘&’} , {90 , ‘)’}};

map<int,char>::const_iterator ci=mp.cend();

cout<< ci->first << ” ” << ci->second << endl; //undefined output

++ci;

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

ci->second=’*’ ; //error,iterator is const

Output

The first output is undefined since the iterator points to invalid storage.
90 )






const_reverse_iterator crbegin( );

This function returns a constant reverse iterator that points to memory before the first element in a map.

Parameters:
none

Return type
const_reverse_iterator

Iteration is done in the decreasing order of the key.

map crend

Code example

map<double,char>mDC{{7.6 , ‘K’} , {9.2 , ‘P’} , {12.3 , ‘P’} , {0.12 , ‘O’}};

map<double,char>::const_reverse_iterator crt=mDC.crend();

++crt;

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

++crt;

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

crt->second=’@’ ; //error,iterator is const type

Output

12.3 P
9.2 P