Michael
Michael

Reputation: 1373

Why we need rbegin and rend?

Since we now have advance() and the prev() to move iterator to go front or go back, and we already have begin() and end().

I wonder is there any situation we better/have to move reverse iterator back and front?

Upvotes: 3

Views: 1352

Answers (7)

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

The need for rbegin()/rend() is because begin() is not the same as rend(), and end() is not rbegin(), see this image from cppreference

enter image description here

This way, you can use any algorithm going forward from beginning to end or backwards from the last to the first element.

Upvotes: 1

onur
onur

Reputation: 47

I guess it is good practise because it seems odd if you start from end and finish in begin. You can easily say last but one by using rbegin.

vector::reverse_iterator itr1;

for (itr1 = vec.rbegin(); itr1 < vec.rend(); itr1++) { 

    if (*itr1 == num) { 

          vec.erase((itr1 + 1).base()); 
    } 
}  

You can use as a function which deletes that Which num want to erase in vector

Upvotes: 1

CygnusX1
CygnusX1

Reputation: 21818

There are examples with for each. However, more general, it allows you to reuse any algorithm or operators that works with iterators with advancing, to do the same thing but in a reverse order.

Upvotes: 0

prog-fh
prog-fh

Reputation: 16910

When you use algorithms like std::for_each(), std::accumulate(), std::find_if()... they systematically progress with ++.
If you want this progression to physically occur backwards, then the reverse iterators are useful.

Upvotes: 1

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122994

Algorithms often take two iterators that specify a range of elements. For example std::for_each:

std::vector<int> x;
std::for_each(x.begin(),x.end(),foo);

If you want to make for_each iterate in reverse order (note: for_each does iterate in order) then neither advance nor prev are of any help, but you can use reverse iterators:

std::for_each(x.rbegin(),x.rend(),foo);

Upvotes: 8

Caleth
Caleth

Reputation: 63049

When you have a function template that takes iterators, and want it to operate on the data in reverse.

E.g.

std::string s = "Hello";
std::string r(s.rbegin(), s.rend());
std::cout << r;

Upvotes: 1

Yksisarvinen
Yksisarvinen

Reputation: 22354

Because using begin() and end() to iterate in reverse looks horrible:

std::vector<int> v {1, 2, 3};
if(!v.empty()) { //need to make sure of that before we decrement
    for(auto it = std::prev(v.end()); ; --it) {
        //do something with it
        if(it == v.begin()) {
            break;
        }
    }
}

Compare it with reverse iterator version:

std::vector<int> v {1, 2, 3};
for(auto it = v.rbegin(); it != v.rend(); it++) {
    //do something with it
}

Upvotes: 4

Related Questions