如何从C ++容器中获取随机元素? [英] How to get a random element from a C++ container?

查看:111
本文介绍了如何从C ++容器中获取随机元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从STL范围中获取[伪]随机元素的好方法是什么?

What is a good way to get a [pseudo-]random element from an STL range?

我能想到的最好的方法是执行 std :: random_shuffle(c.begin(),c.end()),然后从 c.begin()中获取我的随机元素。

The best I can come up with is to do std::random_shuffle(c.begin(), c.end()) and then take my random element from c.begin().

但是,我可能会想要来自 const 容器的随机元素,或者我可能不希望完全改组的成本。

However, I might want a random element from a const container, or I might not want the cost of a full shuffle.

有更好的方法吗?

推荐答案

我发布了此解决方案在其他人引用过的Google+文章上。将其发布到此处,因为它比其他版本稍好一点,因为它通过使用std :: uniform_int_distribution:

I posted this solution on a Google+ article where someone else referenced this. Posting it here, as this one is slightly better than others because it avoids bias by using std::uniform_int_distribution:

#include  <random>
#include  <iterator>

template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
    std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
    std::advance(start, dis(g));
    return start;
}

template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
    static std::random_device rd;
    static std::mt19937 gen(rd());
    return select_randomly(start, end, gen);
}

样本用法为:

#include <vector>
using namespace std;

vector<int> foo;
/* .... */
int r = *select_randomly(foo.begin(), foo.end());

我最终创建了按照类似的方法设计出更好的要点

这篇关于如何从C ++容器中获取随机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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