C ++ enumeration in foreach

Possible duplicates:
List enum in C ++
C ++: Iterating through an enumeration

I have a card class for playing blackjack with the following listings:

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

When I create a deck, I want to write code as follows:

 // foreach Suit in Card::Suit // foreach Rank in Card::Rank // add new card(rank, suit) to deck 

I believe that in C ++ there is no foreach. However, how do I go about renaming?

Thanks Spencer

+7
c ++ enums foreach
source share
1 answer

Typically, to add elements to enum you can do the following:

 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 like:

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

All Articles