How to shuffle a std::vector? Ask Question

How to shuffle a std::vector? Ask Question

I am looking for a generic, reusable way to shuffle a std::vector in C++. This is how I currently do it, but I think it's not very efficient because it needs an intermediate array and it needs to know the item type (DeckCard in this example):

srand(time(NULL));

cards_.clear();

while (temp.size() > 0) {
    int idx = rand() % temp.size();
    DeckCard* card = temp[idx];
    cards_.push_back(card);
    temp.erase(temp.begin() + idx);
}

ベストアンサー1

C++11 以降では、以下を優先する必要があります。

#include <algorithm>
#include <random>

auto rng = std::default_random_engine {};
std::shuffle(std::begin(cards_), std::end(cards_), rng);

Live example on Coliru

rng複数の呼び出しで同じインスタンスを再利用するようにしてください。std::shuffle毎回異なる順列を生成するつもりなら!

さらに、プログラムが実行されるたびに異なるシャッフルシーケンスを作成したい場合は、ランダムエンジンのコンストラクタに次の出力をシードすることができます。std::random_device:

auto rd = std::random_device {}; 
auto rng = std::default_random_engine { rd() };
std::shuffle(std::begin(cards_), std::end(cards_), rng);

C++98 の場合は以下を使用できます:

#include <algorithm>

std::random_shuffle(cards_.begin(), cards_.end());

おすすめ記事