gpt4 book ai didi

c++ - 使用列表而不是值范围的 uniform_int_distribution

转载 作者:行者123 更新时间:2023-11-28 02:28:11 25 4
gpt4 key购买 nike

在尝试运行我的代码后,我查阅了文档和示例,但无法找到将列表提供给 uniform_int_distribution 的方法。那这还不可能吗?

对于在不使用 srand()rand() 的情况下从给定列表中随机选择项目的最佳方法,有没有人有任何建议?

最佳答案

您可以使用 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
}

关于c++ - 使用列表而不是值范围的 uniform_int_distribution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29813269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com