C++ enum in foreach [duplicate]
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));
}
}
精彩评论