我正在制作 BlackJack/21 游戏,因为我正在学习 C++,以便在实际从事项目时获得一些经验。我来自 Java,那里有一个很好的 Collections.shuflfe(...)
功能,但我找不到可靠的(随机的)解决方案来实现与 C++ 类似的结果。
我尝试了以下方法,效果很好,但我想知道是否有更好的方法来执行此操作,因为我觉得我可能不需要使用两个 vector 。但是,我不太清楚我能做些什么来替换它,如果有的话。目前,这对于我的简单纸牌游戏来说已经足够高效了,但我想问一下,是否有任何我可以改进的地方来使它更简单和/或更高效以供将来使用?
template <class T> static vector<T> shuffle(vector<T> input) {
vector<T> values;
vector<int> indexes;
for (int i = 0; i < input.size(); i++) {
indexes.push_back(i);
}
//Seed the random number
srand(static_cast<unsigned int>(time(NULL)));
while(!indexes.empty()) {
//Gets a random index from the currently unused indexes for the input.
int index = rand() % indexes.size();
int location = indexes.at(index);
//Adds the value of the input at the randomly generated location to the new values.
values.push_back(input.at(location));
//remove chosen index from the list
indexes.erase(indexes.begin() + index);
}
return values;
}
最佳答案
std::shuffle
在 <algorithm>
应该是你要找的。这是一个使用示例。
#include <iostream>
#include <algorithm>
#include <vector>
#include <random>
int main () {
std::vector<int> myvector {1,2,3,4,5};
std::random_device rd;
std::default_random_engine gen(rd);
std::shuffle (myvector.begin(), myvector.end(), gen);
for (int& x: myvector) std::cout << ' ' << x;
std::cout << std::endl;
return 0;
}
此示例适用于使用来自 http://www.cplusplus.com/reference/algorithm/shuffle/ 版本的 vector .查看有关 std::shuffle
的更多信息的链接
关于c++ - 有没有更好的方法在 C++ 中改组 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54716035/