一:功能
洗牌算法,给定一个序列,打乱其元素的顺序。
二:用法
#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
int main()
{
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(v.begin(), v.end(), g);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
}
#include <vector>
#include <algorithm>
#include <ranges>
#include <random>
#include <iostream>
//定义扑克牌
struct Card {
unsigned index;
//输出一张扑克牌
friend std::ostream& operator << (std::ostream& s, const Card& card) {
static constexpr std::array<const char*, 13> ranks =
{"Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King"};
static constexpr std::array<const char*, 4> suits =
{"Hearts", "Diamonds", "Clubs", "Spades"};
if (card.index >= 52)
throw std::domain_error("Card index has to be in the range 0..51");
s << ranks[card.index%13] << " of " << suits[card.index/13];
return s;
}
};
int main() {
std::vector<Card> deck(52, Card{});
//生成52张扑克牌
std::ranges::generate(deck, [i = 0u]() mutable { return Card{i++}; });
//按顺序输出
for (auto v : deck)
{
std::cout << "\t" << v << "\n";
if( (v.index + 1) %13 == 0)
{
std::cout << '\n';
}
}
//随机数生成器
std::random_device rd;
std::mt19937 gen{rd()};
//随机乱序输出
std::ranges::shuffle(deck, gen);
for (auto v : deck)
{
std::cout << "\t" << v << "\n";
if( (v.index + 1) %13 == 0)
{
std::cout << '\n';
}
}
}