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.

有帮助吗?

解决方案

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;
}

其他提示

The new C++ 2014 Standard includes corresponding functions for arrays

template <class T, size_t N> reverse_iterator<T*> rbegin(T (&array)[N]);
template <class T, size_t N> reverse_iterator<T*> rend(T (&array)[N]);

In fact they use simply std::reverse_iterator.

So if your compiler does not support these functions you can write yourself

std::reverse_iterator<char *> first( tail );
std::reverse_iterator<char *> last( head );
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top