Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: Nonmember rbegin()/rend() Functions

Since the nonmember begin() and end() functions were added for standard contains in the C++11 revision, why have the nonmember versions of the rbegin() and rend() functions not been added as well? I feel silly after beginning to use the nonmember versions of begin() and end(), only to find that I now have to toggle between the using the member and nonmember function calls. (I realize that it would be trivial to roll my own nonmember versions of rbegin() and rend(), but I'm wondering why this wasn't added to the standard).

Thanks for your input.

like image 915
void-pointer Avatar asked Apr 07 '12 04:04

void-pointer


People also ask

What is rend () in C++?

C++ Vector Library - rend() Function The C++ function std::vector::rend() returns a reverse iterator which points to the reverse end of the vector i.e. beginning of the vector.

What is rend and Rbegin in C++?

rbegin returns an iterator at the end of the string, input . In other words it is a reverse-iterator. rend returns an iterator that points before the first character in the string.

What is rbegin in c++?

The rbegin() is a function in C++ STL. It returns a reverse iterator which points to the last element of the map. The reverse iterator iterates in reverse order and incrementing it means moving towards beginning of map.

Is Rbegin same as end?

The onl difference between begin(), end() and rbegin(), rend() is that: begin() and end() will return bidirectional iterator. rbegin() and rend() will return reverse iterator.


2 Answers

For people who see this later, nonmember rbegin() and rend() are already in C++14.

like image 77
Polymer Avatar answered Oct 05 '22 19:10

Polymer


You can construct reversed range by manually using std::reverse_iterator on the results of std::begin and std::end.

Oddly, there is not a standard factory function for reverse_iterator. If there were, it would probably look like this:

template< typename iter >
std::reverse_iterator< iter > reverse( iter i )
    { return { i }; }

Armed with this, you can do

std::sort( reverse( std::end( my_array ) ), reverse( std::begin( my_array ) ) );

This example saves the trouble of specifying the std::greater comparator, but the reverse_iterator conceivably could adversely affect performance if the compiler can't remove the added complexity from inner loops.

like image 33
Potatoswatter Avatar answered Oct 05 '22 18:10

Potatoswatter