2d 排序卡算法

2d Sorting card algorithm

本文关键字:算法 排序 2d      更新时间:2023-10-16

我正在尝试为一手牌制作一种排序算法,它应该按类型排序,然后按 num 排序,所以输出看起来像 1 俱乐部 5个俱乐部 7 俱乐部 3 钻石 10 钻石 钻石之王等 但我只能让它按花色排序,输出更像 5个俱乐部 1 俱乐部 7 俱乐部 3 钻石 钻石之王 10 钻石等 有谁知道我该怎么做?

void player::handsort() {
int hold[2][13], count=0;
for (int i = 0; i < 13; ++i) {
if (type[i]==Clubs){
hold[1][count]=type[i];
hold[0][count]=hand[i];
count++;
}
}
for (int i = 0; i < 13; ++i) {
if (type[i]==Diamonds){
hold[1][count]=type[i];
hold[0][count]=hand[i];
count++;
}
}
for (int i = 0; i < 13; ++i) {
if (type[i]==Hearts){
hold[1][count]=type[i];
hold[0][count]=hand[i];
count++;
}
}
for (int i = 0; i < 13; ++i) {
if (type[i]==Spades){
hold[1][count]=type[i];
hold[0][count]=hand[i];
count++;
}
}
for (int i = 0; i < 13; ++i) {
hand[i]=hold[0][i];
type[i]=hold[1][i];
}
}

我会考虑将您的实现更改为更模块化的东西。

enum Suit { CLUB, DIAMOND, HEARTS, SPADES };
struct Card {
Suit suit;
int   num;
bool operator<(Card c) const { 
if (suit != c.suit) 
return suit < c.suit;
return num < c.num;
}
};
void handsort(std::vector<Card> &hand) { std::sort(hand.begin(), hand.end()); }

请记住,这是C++。利用自由抽象!