为 Multimap 中的特定键选择随机元素 [英] Selecting a random element for a specific key in a Multimap

查看:35
本文介绍了为 Multimap 中的特定键选择随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为多映射中的特定键选择随机元素.例如:

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. 获取迭代器范围 - 你已经有了这个
  2. 计算范围的大小

  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);

现在生成一个随机索引:

Now generate a random index:

std::size_t idx = std::rand() % sz;//愚蠢的例子

将迭代器移动到 idx-th 位置:

Move the iterator to the idx-th position:

std::advance(iterators.first, idx);

现在 iterators.first 指向一个随机的哺乳动物.

Now iterators.first is pointing at a random mammal.

这篇关于为 Multimap 中的特定键选择随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆