STL map: reverse iterator for lower_bound?

Q

qlin88

Hi,

In STL multi-map, the lower_bound, upper_bound,equal_range all
return an iterator. Now ifone wants to iterate from an upper bound
towards a lower bound, what would be the best way to do it?

I tried to interate backwards with an iterator, but the begin()
element was not properly included.

Thanks for your help.
 
E

Erik Wikström

Hi,

In STL multi-map, the lower_bound, upper_bound,equal_range all
return an iterator. Now ifone wants to iterate from an upper bound
towards a lower bound, what would be the best way to do it?

I tried to interate backwards with an iterator, but the begin()
element was not properly included.

You can use reverse_iterators and rend():

#include <iostream>
#include <map>

int main()
{
std::multimap<int, int> m;
for (int i = 0; i < 10;++i)
{
m.insert(std::make_pair(i, i));
m.insert(std::make_pair(i, 2*i));
}

//for (
std::multimap<int, int>::iterator it = m.begin();
it != m.end();
++it)
// std::cout << it->first << "\t" << it->second << "\n";


std::multimap<int, int>::iterator upper = m.upper_bound(4);
std::multimap<int, int>::reverse_iterator r(upper);

for (;r != m.rend();++r)
std::cout << r->first << "\t" << r->second << "\n";
}
 
J

Jiri Palecek

Hi,

In STL multi-map, the lower_bound, upper_bound,equal_range all
return an iterator. Now ifone wants to iterate from an upper bound
towards a lower bound, what would be the best way to do it?

You can convert any (bidirectional) iterator to its reverse by something
like that:

typedef std::reverse_iterator<Iter> rev_it;
std::for_each(rev_it(end), rev_it(begin), ...);

Regards
Jiri Palecek
 
A

Andrew Koenig

In STL multi-map, the lower_bound, upper_bound,equal_range all
return an iterator. Now ifone wants to iterate from an upper bound
towards a lower bound, what would be the best way to do it?
I tried to interate backwards with an iterator, but the begin()
element was not properly included.

Rule of thumb: decrement before you use the iterator; increment after you
use it. So:

it = x.begin();
while (it != x.end()) {
// do something with *it
++it;
};

And, going the other way:

it = x.end();
while (it != x.begin()) {
--it;
// do something with *it
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top