这个问题已经在这里有了答案:




已关闭10年。






我有二十一点游戏的纸牌类,其中包含以下枚举:

enum Rank { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King };
enum Suit { Clubs, Diamonds, Hearts, Spades };

当我创建套牌时,我想编写如下代码:
// foreach Suit in Card::Suit
//   foreach Rank in Card::Rank
//     add new card(rank, suit) to deck

我相信C++中没有foreach。但是,如何遍历枚举?

谢谢,
斯宾塞

最佳答案

通常可以在enum中添加元素以简化此操作:

enum Rank {
    Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King,
    RankFirst = Ace, RankLast = King
};
enum Suit {
    Clubs, Diamonds, Hearts, Spades,
    SuitFirst = Clubs, SuitLast = Spades
};

然后,您可以将循环编写为:
for (int r = RankFirst; r <= RankLast; ++r) {
    for (int s = SuitFirst; s <= SuitLast; ++s) {
        deck.add(Card((Rank)r, (Suit)s));
    }
}

关于foreach中的C++枚举,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2941890/

10-10 13:22