Search code examples
c++pointersiteratorreverse

Standard way for reverse pointer iterators


Is there something like rbegin and rend for pointers?

I have pointers to the head and tail of a c-style string but would like to create reverse iterators for them.

I want to know if there is a way to do this that is supplied by the standard, or if I have to write my own code for this.

EDIT: I am using low level code for a reason. No std::basic_string and such. Goal is to use std::find to find last occurrence of a value.


Solution

  • Use std::reverse_iterator:

    #include <iostream>
    #include <iterator>
    
    int main() {
        const char* s = "abc";
        std::reverse_iterator<const char*> first(s + 3);
        std::reverse_iterator<const char*> last(s);
        for( ; first != last; ++first) {
            std::cout << *first;
        }
        std::cout << '\n';
        return 0;
    }