How to reverse iterate a ValueMap?

Normally i use this:

for (auto it = valuemap.begin(); it != valuemap.end(); it++)
{
// do stuff
}

but i need reverse iterate the value map, the code below doesn´t work

 for (auto it = valuemap.end(); it != valuemap.begin(); it--)
 {
    // do stuff
 }

There’s no real concept or good reason to reverse iterate on a map container. ValueMap is an alias for std::unordered_map and so there’s no reverse iterator. If you were using a ValueVector you could use rbegin() and rend() to reverse iterate through a contiguous container like std::vector.

Just for the sake of completeness, as @stevetranby was already pointing out, that there is no good reason for it:

std::reverse_iterator<ValueMap::const_iterator> crbegin(valuemap.cbegin());
std::reverse_iterator<ValueMap::const_iterator> crend(valuemap.cend());

for (auto &&it = crbegin; it != crend; ++it)
{
    // do stuff
}

Maybe you should also use const iterators :wink:

2 Likes