I'm interested in the implementation of the reverse iterator with rbegin(), rend() and operator++ of the class string, I can't find it in google, how can I do it? thanks in advance for any help or any link
3 Answers
You could look in the implementation header files. (e.g. /usr/include/c++/4.1.2/string on Linux). This will typically just pull in a load of other headers where the real meat lies, such as bits/basic_string.h.
I don't know where they reside for e.g. VC++, but you can usually just get Intellisense to find it by creating a std::string, selecting it and pressing F12.
1 Comment
There is a basic implementation of reverse_iterator in the STL.
It is templatized by the Iterator to be reverted.
The idea is quite simple, if you look at a range:
[first, second, .... last]
^ ^
begin end
rend rbegin
There is extra-work done, compared to a pure reverse iterator using this implementation, since for each dereference, you need to copy the iterator you hold, decrement it, and then dereference it.
Comments
Reverse iteration for bidirectional iterators is implemented in the std::reverse_iterator template.
The implementation of reverse iterators for std::string doesn't take more than:
template <xxx>
class basic_string
{
public:
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
reverse_iterator rbegin() { return reverse_iterator(this->end()); }
const_reverse_iterator rbegin() const { return const_reverse_iterator(this->end()); }
reverse_iterator rend() { return reverse_iterator(this->begin()); }
const_reverse_iterator rend() const { return const_reverse_iterator(this->begin()); }
//...
};
(Copied from GCC's implementation.)