tags:

views:

461

answers:

2

I want to insert something into a STL list in C++, but I only have a reverse iterator. What is the usual way to accomplish this?

This works: (of course it does)

std::list<int> l;
std::list<int>::iterator forward = l.begin();
l.insert(forward, 5);

This doesn't work: (what should I do instead?)

std::list<int> l;
std::list<int>::reverse_iterator reverse = l.rbegin();
l.insert(reverse, 10);
+5  A: 

l.insert(reverse.base(), 10); will insert '10' at the end, given your definition of the 'reverse' iterator. Actually, l.rbegin().base() == l.end().

Johannes Schaub - litb
+2  A: 

Essentially, you don't. See 19.2.5 in TCPPPL.

The reverse_iterator has a member called base() which will return a "regular" iterator. So the following code would work in your example:

l.insert(reverse.base(), 10);

Be careful though because the base() method returns the element one after the orginal reverse_iterator had pointed to. (This is so that reverse_iterators pointing at rbegin() and rend() work correctly.)

Mike Kale