2015-04-23 22 views
0

我试图运行我的代码后查找了文档和示例,但无法找到将列表提供给uniform_int_distribution的列表的方法。那么这是不可能的?uniform_int_distribution使用列表而不是一系列值

有没有人有任何建议,从最好的方式随机选择一个给定的列表中的项目,而不使用srand()rand()

+2

使用'uniform_int_distribution'以产生'[0,列表中的一个整数.size())'并在该索引处选择该项目。 –

+0

[本页]底部有一个示例(http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution)。使用TC的建议来调整它应该是微不足道的。 – Praetorian

回答

2

可以生成使用uniform_int_distribution在正确的范围内的随机数,然后使用接std::next,像列表的元素:

#include <algorithm> 
#include <iostream> 
#include <list> 
#include <random> 

int main() 
{ 
    std::random_device rd; 
    std::mt19937 rng(rd()); 
    std::list<char> lst{'a', 'b', 'c', 'd'}; 
    std::uniform_int_distribution<std::size_t> uid(0, lst.size() - 1); // range [0, size-1] 
    std::size_t pos = uid(rng); // random index in the list 
    auto elem = *std::next(lst.begin(), pos); // pick up the element 
    std::cout << elem << std::endl; // display it 
} 
相关问题