C ++如何从向量列表中选择随机变量?

时间:2020-04-17 07:29:14

标签: c++ vector random

我正在尝试创建一个从矢量列表中随机选择客户名称的函数。下面是我尝试使用mt19937引擎实现此功能的方法

Carly:Cat:ABCCCCE.
Dodgy Dan:Dog:BCACECC.
Ernie:Ettin:AABCCDD.
Sally:Snake:AEEEEEE.
例如,

上面是向量列表的内容。如果该功能正常工作,则有可能随机返回Carly,Dodgy Dan,Ernine或Sally(客户名)。

struct Customer {
    std::string customerName;
};

float randomCus(const vector<Customer>& customerList,const Builder& b) {

float total;
std::random_device random_device;
std::mt19937 engine{random_device()};
std::uniform_int_distribution<int> dist(0, customerList.size() - 1);

for(Customer x:customerList) {
for(int i=0; i < customerList.size(); i++){

int random_element = x.customerName[dist(engine)];
cout << random_element <<  "This is a random customer name: ";
}
return total;
}

预期输出可能包括

Carly was randomlly selected
Dodgy Dan was randomlly selected 

1 个答案:

答案 0 :(得分:0)

您要添加一个随机的客户名称的字符。

void randomCus(const vector<Customer>& customerList,const Builder& b) {

std::random_device random_device;
std::mt19937 engine{random_device()};
std::uniform_int_distribution<int> dist(0, customerList.size() - 1);

int random_index = dist(engine);
std::cout << "This is a random customer name: " << customerList[random_index].customerName;

}

每次调用该函数都会打印一个随机名称。

编辑:缺少会员通话&&错字