Andrew
Andrew

Reputation: 636

How do you insert with a reverse_iterator

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

Upvotes: 30

Views: 15759

Answers (3)

lakeweb
lakeweb

Reputation: 1939

Just in case it is helpful, as this it the first hit on a search, here is a working example of using rbegin. This should be faster than using std::stringstream or sprint. I defiantly call a member fmt_currency many thousands of times in some print jobs. The std::isalnum is for handling a minus sign.

std::wstring fmt_long(long val) {//for now, no options? Just insert commas
    std::wstring str(std::to_wstring(val));
    std::size_t pos{ 0 };
    for (auto r = rbegin(str) + 1; r != str.rend() && std::isalnum(*r); ++r) {
        if (!(++pos % 3)) {
            r = std::make_reverse_iterator(str.insert(r.base(), L','));
        }
    }
    return str;
}

Upvotes: 0

Mike Kale
Mike Kale

Reputation: 4133

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

Upvotes: 17

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507433

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

Upvotes: 32

Related Questions