Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you insert with a reverse_iterator

Tags:

c++

stl

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);
like image 382
Andrew Avatar asked Nov 19 '08 00:11

Andrew


2 Answers

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

like image 72
Johannes Schaub - litb Avatar answered Oct 13 '22 17:10

Johannes Schaub - litb


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.)

like image 37
Mike Kale Avatar answered Oct 13 '22 16:10

Mike Kale