这里我们可以定义一个扑克牌的结构体,
模拟扑克牌的实现和手牌排序(也就是完成对结构体的排序)
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//首先定义一个结构体
struct Poker
{
char type; //花色
int point; //大小
};
enum
{
SPADES, //黑桃
HEARTS, //红桃
CLUBS, //梅花
DIAMONDS, //方片
JOKER //王
};
//扑克牌的输入
void inputpoker(Poker * pk)
{
scanf("%c%d", &pk->type, &pk->point);
pk->type -= 'a'; //目的是为了让输入'a'表示黑桃,'b'表示红桃,'c'表示梅花,'d'表示方片,'e'表示王
if (pk->type == JOKER)
{
pk->point += 13;
}
while (getchar() != '\n');
}
void outputpoker(Poker k)
{
char * type[5] = { "黑桃", "红桃", "梅花", "方片", "" };
char * point[16] = { "", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "小王", "大王" }; //e1,e2为分别为小王大王
printf("%s%s\n", type[k.type], point[k.point]);
}
//对手牌的排序,也就是结构体的排序规则
bool cmppoker(Poker a, Poker b)
{
return (a.point < b.point) || (a.point == b.point && a.type > b.type);
}
//手牌的排序类似于插入排序
void InsertSort(Poker * src, int n, bool (*cmp)(Poker, Poker) = cmppoker)
{
int i, j;
Poker tmp;
for (i = 1; i < n; ++i)
{
tmp = src[i];
for (j = i; j > 0 && cmp(tmp, src[j - 1]); --j) //通过函数指针传入排序规则
{
src[j] = src[j - 1];
}
src[j] = tmp;
}
}
//常见的手牌排序,3为最小,大王最大,小王次大,接着为2,1
bool PokerCmpPare(Poker a, Poker b)
{
if (a.point <= 2)
{
a.point += 11;
}
else if (a.point <= 13)
{
a.point -= 2;
}
if (b.point <= 2)
{
b.point += 11;
}
else if (b.point <= 13)
{
b.point -= 2;
}
return (a.point < b.point) || (a.point == b.point && a.type < b.type);
}
int main()
{
Poker p[5];//用五张手牌测试程序
int i;
for (i = 0; i < 5; ++i)
{
inputpoker(p + i);
}
//InsertSort(p, 5);
InsertSort(p, 5, PokerCmpPare);
for (i = 0; i < 5; ++i)
{
outputpoker(p[i]);
}
//Poker p;
//inputpoker(&p);
//outputpoker(p);
system("pause");
return 0;
}