I've been having some trouble with getting reverse iterators to work along with the standard algorithms. Since they only accept a normal iterator
Huh? Here's three that seem to work pretty well with reverse iterators:
Code:
vector<int> v;
for(int i=0; i<9; i++)
{
v.push_back(i);
}
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout<<endl;
copy(v.rbegin(), v.rend(), ostream_iterator<int>(cout, " "));
cout<<endl;
v.push_back(0);
copy(v.rbegin(), v.rend(), ostream_iterator<int>(cout, " "));
cout<<endl;
vector<int>::reverse_iterator pos = find(v.rbegin(), v.rend(), 0);
cout<<distance(v.rbegin(), pos)<<endl;
Is there a way to make a reverse iterator work with the algorithms?
Which algorithm? If you want to use erase(), you can do this:
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
vector<int> v;
for(int i=0; i<9; i++)
{
v.push_back(i);
}
v.push_back(0);
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout<<endl;
vector<int>::reverse_iterator pos = find(v.rbegin(), v.rend(), 0);
v.erase((++pos).base());
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout<<endl;
return 0;
}
The way I understand it, a reverse iterator and an iterator both point to the same place, but a reverse iterator's value is defined to be one ahead of where it is pointing i.e. closer to the front of the container. For example, with an iterator, end() points to one past the last element, and if you dereference end() you will access memory that is out of bounds. For a reverse iterator, you might expect that rbegin() points to the last element(vs. one past the last element), but rbegin() also points to the one past the last element. However, if you dereference rbegin(), you get the last element--not the illegal memory one past the last element that rbegin() is pointing to. In a similar fashion, begin() and rend() both point to the first element.
If you convert a reverse iterator to an iterator using base(), the value switches from the value that's one ahead of where the reverse iterator is pointing--> to the value at the position the reverse iterator is pointing. In the example, pos is physically pointing to one past the end, but since it is a reverse iterator, when you dereference it, you get the value one ahead of where the reverse iterator is pointing, which is the last element. If you convert that reverse iterator to an iterator with base(), then since it is now a regular iterator, when you dereference it, you will get the value where the iterator is pointing, and that is one past the end, which is out of bounds. So, to use erase(), I advanced the pointer one spot and then converted it to a regular iterator.
I really have no idea if that is at all helpful because I have no idea what your question is.