Picking a random element from STL multimap

Discussion in 'C++' started by Steve, Nov 28, 2009.

  1. Steve

    Steve Guest

    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, Nov 28, 2009
    #1
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.