开发者

C++ enum in foreach [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicates:

Enumerate over an enum in C++

C++: Iterate through an enum

I've have a card class for a blackjack game with the following enums:

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

When I create the deck I want to write the code like this:

// foreach Suit in Card::Suit
//   foreach Rank in Card::Rank
//     add new开发者_运维技巧 card(rank, suit) to deck

I believe there is no foreach in c++. However, how do I traverse an enum?

Thanks, Spencer


It is common to add elements to the enum to facilitate this:

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
};

Then you can write your loops as:

for (int r = RankFirst; r <= RankLast; ++r) {
    for (int s = SuitFirst; s <= SuitLast; ++s) {
        deck.add(Card((Rank)r, (Suit)s));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜