因为我想要按照斗地主的规则对用户手牌进行排序,我直接用一个string数组hand[]来储存所有的牌,并从大到小排序,接下来我只需要保存每一个用户所拥有的hand数组的下标,并将下标由大到小排序,输出时即可获得已经排好序的手牌。
直接看代码,比较好懂
#include <iostream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
//按照从小到大的顺序 保存54张牌,w表示小王,W表示大王
string hand[] = { "3","3","3","3","4","4","4","4","5","5","5","5","6","6","6","6","7","7","7","7","8",
"8","8","8","9","9","9","9","10","10","10","10","J","J","J","J","Q","Q","Q","Q","K",
"K","K","K","A","A","A","A","2","2","2","2","w","W" };
int sub[54];//用来对应hand数组的每个元素的下标
//随机发牌
void deal_card(string hand[], int player[3][20]) {
int leftNum = 54;//剩余牌的数量
int ranNum;//随机下标
for (int i = 0; i < 17; i++) {
for (int j = 0; j < 3; j++) {
srand((unsigned)time(NULL));//定义seed种子,用于rand生成不重复的随机数
ranNum = rand() % leftNum;//在[0,leftNum)中生成随机数
player[j][i] = sub[ranNum];
sub[ranNum] = sub[leftNum - 1];//将随机数对应下标的元素和最后一个元素 进行交换
leftNum--;
}
}
}
//对用户的手牌进行从大到小的排序
void sort_card(int player[3][20]) {
for (int i = 0; i < 3; i++) {
sort(player[i], player[i] + 17, greater<int>());//将玩家手牌按从大到小排序
}
}
//输出三个玩家的手牌和剩下的底牌
void print_card(int player[3][20]){
for (int i = 0; i < 3; i++) {
cout << "玩家" << i + 1 << "的手牌:";
for (int j = 0; j < 17; j++) {
cout << setw(3) << hand[player[i][j] - 1];
}
cout << endl;
}
cout << "三张底牌:";
for (int i = 0; i < 3; i++) {
cout << setw(3) << hand[sub[i] - 1];
}
}
int main()
{
int player[3][20];//三个玩家的手牌
for (int i = 0; i < 54; i++) {//对sub初始化
sub[i] = i + 1;
}
deal_card(hand,player);
sort_card(player);
print_card(player);
cout << endl;
return 0;
system("pause");
}
输出结果: