【问题标题】:C++ how to choose a random variable from a vector list?C ++如何从向量列表中选择一个随机变量?
【发布时间】:2020-04-17 07:29:14
【问题描述】:

我正在尝试创建一个从向量列表中随机选择客户姓名的函数。下面是我使用 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 

【问题讨论】:

  • 您正在从每个customerName 中选择一个随机字符。您想选择customerList 的随机元素

标签: c++ vector random


【解决方案1】:

您正在访问客户名称的随机字符。

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;

}

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

编辑:缺少成员调用&&错字

【讨论】:

  • 这在第 7 行“没有合适的转换函数从“lambda []auto ()->auto”到“int”存在”和第 8 行的最后一个 >
  • @DavidLing 现在应该得到修复。忘记访问字符串成员。
  • 它不喜欢这一行 int random_index = dist(engine)];
  • 这确实符合并运行,但它一直返回相同的名称。
  • 可以播种吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
相关资源
最近更新 更多