簡體   English   中英

C++ 如何從向量列表中選擇隨機變量?

[英]C++ how to choose a random variable from a vector list?

我試圖創建一個從向量列表中隨機選擇客戶名稱的 function。 下面是我使用 mt19937 引擎對這個 function 的嘗試

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

例如,上面是向量列表的內容。 如果使用 function 有可能隨機退回 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;
}

預期的 output 可能包括

Carly was randomlly selected
Dodgy Dan was randomlly selected 

您正在訪問客戶名稱的隨機字符。

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;

}

每次調用 function 時都會打印一個隨機名稱。

編輯:缺少會員電話&&錯字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM