我有一个允许重复的向量,我想随机选择一个元素,其概率代表元素重复的次数。
例如 - 对于下面的向量,6应该具有最高的被选择概率。我想过使用rand()
,但我不确定如何合并概率。
vector A = [ 0, 0, 2, 2, 4, 5, 1, 6, 6, 6]
谢谢
答案 0 :(得分:0)
也许是这样的(未经测试!):
#include <vector>
#include <random>
#include <iostream>
int main()
{
std::vector<size_t> A{0, 0, 2, 2, 4, 5, 1, 6, 6, 6};
static thread_local std::mt19937 g{std::random_device{}()};
static thread_local std::uniform_int_distribution<size_t> d{0,A.size()};
std::cout << A[d(g)] << std::endl;
}
答案 1 :(得分:-1)
我认为您正在以正确的方式获得自定义的价值分配。请参阅以下代码,该代码演示了对矢量的访问。希望它有所帮助。
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <vector>
int main()
{
std::vector<int> A { 0, 0, 2, 2, 4, 5, 1, 6, 6, 6 };
std::srand(std::time(0)); // use current time as seed for random generator
int random_pos = std::rand() % A.size(); // Modulo to restrict the number of random values to be at most A.size()-1
int random_val = A[random_pos];
}