tags:

views:

194

answers:

1

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

+7  A: 

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));
    }
}
MtnViewMark
I tried that and got an error. Here what I got working:for (int suit = Card::Clubs; suit <= Card::Spades; suit++) for (int rank = Card::Ace; rank <= Card::King; rank++) cards.push(Card(Card::Rank(rank), Card::Suit(suit)));
Spencer
You're right - that's what I get for answering SO questions just before going to bed. I've updated the code with something that compiles now.If you follow the links to the "duplicates", you'll find several more exotic solutions that enable you to apply ++ to the Enum itself. They provide more type safety (no casts). However, the simpler solution provided here I've seen in tons of production C++ code.
MtnViewMark