问题
How can I select a random element for a specific keys in a multimap. For example:
multimap<string, string> map;
map.insert(pair<string, string>("Mammal", "Tiger"));
map.insert(pair<string, string>("Mammal", "Chicken"));
map.insert(pair<string, string>("Mammal", "Fox"));
map.insert(pair<string, string>("Fish", "Clown Fish"));
map.insert(pair<string, string>("Fish", "Ray"));
In the above, what would be the best way to get a random "Mammal"?
I know I can get the iterators for the "Mammal" so:
pair<MultiMapIt,MultiMapIt>iterators = mMultiMap.equal_range("Mammal");
// loop through each... and select one.
But I am sure there is a better solution... perhaps using the iterator as numbers..
Thanks
回答1:
Inserting comments as answer:
- Get the iterator range - you have this already
Calculate the size of the range
std::size_t sz = std::distance(iterators.first, iterators.second);
Now generate a random index:
std::size_t idx = std::rand() % sz; // stupid example
Move the iterator to that position
std::advance(iterators.first, sz);
Now iterators.first
is pointing at a random mammal.
来源:https://stackoverflow.com/questions/11431631/selecting-a-random-element-for-a-specific-key-in-a-multimap