簡體   English   中英

在C ++中生成唯一的隨機數

[英]Generating Unique Random Numbers in C++

C ++初學者在這里。 我在下面有這段代碼。 不僅限於此,這是我需要幫助的部分。 我需要生成隨機數(0-9)並將其推回到向量中。 我希望這些隨機數是唯一的。 我怎么做? 另外,我不能使用std :: find(std :: begin(vector),std :: end(vector),a)。 非常感謝大家。

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {

  int digit = 0;
  int randNo = 0;
  cin >> digit;       
  srand((unsigned)time(NULL));
  vector <int> randG(digit);
            for(int i = 0; i < randG.size(); i++){
                    randNo = rand() %10;
                    randG.at(i) = randNo;
            }
  }

如果您不太在乎效率,並且希望在不替換{a,a + 1,...,b}的情況下進行均勻采樣,則可以創建vector<int> vstart ,其中vstart[i]=a+i 之后,如果要k個樣本並將其存儲在v_samplesnumrand在[0, v.size() )中生成一個隨機數numrand ,將vstart[numrand]推入vsamples ,然后從vstart刪除采樣項(刪除對應於“無需更換”部分),重復此k次。 刪除可能會很昂貴,因此改組vstart並選擇改組后的向量的前k個條目。

改組時要小心,因為您可能無法獲得統一的改組: https : //www.i-programmer.info/programming/theory/2744-how-not-to-shuffle-the-kunth-fisher-yates-algorithm。 html 最好的方法是使用<algorithm>庫中的shuffle函數: http : //www.cplusplus.com/reference/algorithm/shuffle/ ,或者自己編寫經過驗證的shuffle(Knuth shuffle是解決此問題的經典解決方案)。

暫無
暫無

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

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