Selecting a random element for a specific key in a Multimap

ε祈祈猫儿з 提交于 2019-12-11 07:54:56

问题


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:

  1. Get the iterator range - you have this already
  2. Calculate the size of the range

    std::size_t sz = std::distance(iterators.first, iterators.second);

  3. Now generate a random index:

    std::size_t idx = std::rand() % sz; // stupid example

  4. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!