如何shuffle std :: vector? [英] How to shuffle a std::vector?

查看:141
本文介绍了如何shuffle std :: vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种通用的,可重复使用的方法来洗刷C ++中的 std :: vector 。这是我目前做的,但我认为它不是很有效率,因为它需要一个中间数组,它需要知道项目类型(在这个例子中的DeckCard):

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);
}


推荐答案

可以使用:

#include <algorithm>

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

从C ++ 11开始,您应该更喜欢:

From C++11 onwards, you should prefer:

#include <algorithm>
#include <random>

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

确保重复使用引擎 shuffle 多次调用

Make sure to reuse the same instance of engine throughout multiple calls to shuffle if you intend to generate different permutations everytime.

这篇关于如何shuffle std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆