2016-04-22 5 views
2
#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <cstdlib> 


int main() { 
    std::vector<short> a(256); 
    for (short x = 0; x != 256; ++x) { 
     a[x] = x; 
    } 
    for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl; 
    std::cout << std::endl; 

    std::srand(11); 

    std::random_shuffle(a.begin(), a.end()); 
    for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl; 
    std::cout << std::endl; 

    for (short x = 0; x != 256; ++x) { 
     a[x] = x; 
    } 
    for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl; 
    std::cout << std::endl; 

    std::srand(11); 

    std::random_shuffle(a.begin(), a.end()); 
    for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl; 
} 

ここに私のコードです。私が期待していることは、明らかに、両方の時間が同じシャッフルです。私が得ることは、シャッフルは打ち上げの間に一貫しているが、彼らは異なっており、サンドを無視しているようだ!私はここで間違って何をしていますか?std :: random_shuffleはシードされていません

答えて

2

std::random_shuffleの場合、どの乱数ジェネレータが使用されるかは実装定義ですが、std::randの使用は保証されません。

代わりstd::shuffleを使用し、それに乱数ジェネレータ渡すことができます。

std::random_device rd; 
std::mt19937 g(rd()); 
std::shuffle(a.begin(), a.end(), g); 

LIVE

2

ご使用のstd::random_shuffleのバージョンは廃止予定です。

はまた

(前回参照リンクから)...機能std::randが頻繁に使用されている注意してください。ここでのキーワードはしばしばない常に

同じシーケンスが常に作成されていることを確認したい場合は、特定の乱数関数を渡すか、発電機を渡す関数std::shuffleを使用してください(C++ 11 "new" PRNG classes)。

関連する問題