2014-05-20 50 views
0

我需要類似rand()但我只需要每個數字一次。C++ rand()每個數字只有一次

在示例中,我有10個名爲數字(1-10)的「.txt」文件。 我想讀取裏面的內容,並隨機選擇。

我不想的1.txt - > 2.txt - > 3.txt - > ... 但隨機的東西像

5.txt - > 4.txt - >的1.txt - > ...

每個數字只能拿出一次

是否有一個「簡單」的方式來做到這一點?

string Path = "./Questions_Niko/" + random + ".txt"; 
+0

如果真正的應用是以可預測的名稱格式(即{number} .txt)遍歷文件,則可以使用正則表達式來提取所需的文件 –

回答

1

有幾種方法。例如,你可以使用標準算法std::random_shuffle在頭<algorithm>

宣佈例如

#include <algorithm> 
#include <iterator> 

//... 

int main() 
{ 
    int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 

    std::random_shuffle(std::begin(a), std::end(a)); 

    for (int i : a) 
    { 
     // some stuff 
    } 
} 

另一種方法是使用標準的類std::bitset,並設置相應的位在設置爲已經選擇的號碼。

6

創建你想要的號碼vector,並使用std::shuffle

然後按順序遍歷向量。

+0

這是正確的想法,但請使用['shuffle'](http://en.cppreference.com/w/cpp/algorithm/random_shuffle)而不是'random_shuffle'。甚至有一個OP在鏈接頁面上想要的例子 – Praetorian

+0

@Praetorian,很公平,我會編輯。 – merlin2011

+0

工作過,謝謝! – user3566608

0

創建每個結果的散列表。如果存在,則重新生成它。

-1

使用srand()將解決您的問題

//Randomize seed 
srand(time(NULL)); 

for(i to size) 
    Arr[i]=rand()%size 
0

std::random_shuffle可能適合您的需求,但如果你不能/不想,你可以借mshuffle:

int mix[10]; 
int swap; 
for (i = 9; i >= 0; i--) { 
    int j = rand() % i; 
    swap = mix[j]; 
    mix[j] = mix[i]; 
    mix[i] = swap; 
} 

假設你」首先調用srand(),這會混合名爲mix的數組。它不需要是一個int s的數組。

相關問題