在unordered_map中选择随机元素 [英] Select random element in an unordered_map

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

问题描述

我这样定义unordered_map:

std::unordered_map<std::string, Edge> edges;

是否有一种有效的方法可以从unordered_map边缘中选择一个随机边缘?

Is there a efficient way to choose a random Edge from the unordered_map edges ?

推荐答案

C ++ 11之前的解决方案:

Pre-C++11 solution:

std::tr1::unordered_map<std::string, Edge> edges;
std::tr1::unordered_map<std::string, Edge>::iterator random_it = edges.begin();
std::advance(random_it, rand_between(0, edges.size()));

C ++ 11及更高版本的解决方案:

C++11 onward solution:

std::unordered_map<std::string, Edge> edges;
auto random_it = std::next(std::begin(edges), rand_between(0, edges.size()));


选择有效随机数的函数由您选择,但是请确保当edges不为空时,它返回范围为[0 ; edges.size() - 1]的数字.


The function that selects a valid random number is up to your choice, but be sure it returns a number in range [0 ; edges.size() - 1] when edges is not empty.

std::next 函数只是包装了

The std::next function simply wraps the std::advance function in a way that permits direct assignation.

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

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