Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ enum in foreach [duplicate]

Tags:

c++

foreach

enums

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

like image 711
Spencer Avatar asked May 31 '10 07:05

Spencer


1 Answers

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));
    }
}
like image 72
MtnViewMark Avatar answered Oct 23 '22 04:10

MtnViewMark