Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Picking a random element from STL multimap

2 views
Skip to first unread message

Steve

unread,
Nov 28, 2009, 8:51:52 AM11/28/09
to
Hello,

when a multimap has multiple elements for a certain key, I want to
pick any random one of them.
I use equal_range to get the bounds iterators, and then try to add a
random number to the lower iterator, but the compiler complains that
there is no operator+.

map<char, int> myMap;

(... fill map with elements)

pair<multimap<char,int>::iterator,multimap<char,int>::iterator> ret =
myMap.equal_range('a');
multimap<char,int>::iterator firstIter = ret.first;
long numMatches = myMap.count('a');
int r = (random number between 0 and numMatches);
multimap<char,int>::iterator randomIter = firstIter +r;


I'm sure I've used +/- on iterators before, but maybe they only work
on other containers?

Is there a way to achieve this? I'm happy to go a completely different
route if there's a more efficient way.

Thanks

Steve


Steve

unread,
Nov 28, 2009, 8:57:40 AM11/28/09
to
(P.S. changed my nickname to 'Steve', was formerly 'petertwocakes')

joseph cook

unread,
Nov 28, 2009, 9:46:01 AM11/28/09
to

OK,
I'm not going to comment on your "radom" method, because I'll assume
that it is meeting your purposes.
However, as for the iterators, look at std::advance(InputIterator&
i, Distance d) which generically advances an iterator "i", 'd'
steps.
You cannot advance all iterators with operator+/-, just Random
Access Iterators

Hope that helps,
Joe Cook

Steve

unread,
Nov 28, 2009, 9:51:37 AM11/28/09
to

Thanks Joe, that's exactly what I needed.
Steve

0 new messages