lau*_*ent 86 c++ shuffle stdvector
我正在寻找一种通用的,可重用的方式来改变std::vectorC++中的一个.这就是我目前的做法,但我认为它不是很有效,因为它需要一个中间数组,它需要知道项目类型(在这个例子中是DeckCard):
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);
}
Run Code Online (Sandbox Code Playgroud)
use*_*016 182
对于C++ 98,您可以使用:
#include <algorithm>
#include <random>
auto rng = std::default_random_engine {};
std::shuffle(std::begin(cards_), std::end(cards_), rng);
Run Code Online (Sandbox Code Playgroud)
从C++ 11开始,你应该更喜欢:
#include <algorithm>
std::random_shuffle(cards_.begin(), cards_.end());
Run Code Online (Sandbox Code Playgroud)
如果您打算每次都生成不同的排列,请务必重复使用rng多个调用中的相同实例std::shuffle!
http://www.cplusplus.com/reference/algorithm/shuffle/
// shuffle algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::shuffle
#include <vector> // std::vector
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock
int main ()
{
// obtain a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine e(seed);
while(true)
{
std::vector<int> foo{1,2,3,4,5};
std::shuffle(foo.begin(), foo.end(), e);
std::cout << "shuffled elements:";
for (int& x: foo) std::cout << ' ' << x;
std::cout << '\n';
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 8
除了@Cicada所说的,你应该先播种,
srand(unsigned(time(NULL)));
std::random_shuffle(cards_.begin(), cards_.end());
Run Code Online (Sandbox Code Playgroud)
Per @ FredLarson的评论:
此版本的random_shuffle()的随机性源是实现定义的,因此它可能根本不使用rand().那么srand()就没有效果了.
所以YMMV.
它可以更简单,可以完全避免播种:
#include <algorithm>
#include <random>
// Given some container `container`...
std::shuffle(container.begin(), container.end(), std::random_device());
Run Code Online (Sandbox Code Playgroud)
每次程序运行时,这都会产生新的随机播放。由于代码简单,我也喜欢这种方法。
这是可行的,因为我们只需要std::shuffle一个满足UniformRandomBitGenerator要求std::random_device的 。
注意:如果重复洗牌,最好将 存储random_device在局部变量中:
std::random_device rd;
std::shuffle(container.begin(), container.end(), rd);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66941 次 |
| 最近记录: |