Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Algorithms
Expertise: Beginner
May 6, 1997



Application Security Testing: An Integral Part of DevOps

Initializing a deck of cards using a for-loop

I have two enumerated types: enum suit_type{club,diamond,heart,spade} and enum rank_type{ace,two,...,queen,king}. In structure CARD, I have the variables suit_type suit and rank_type rank. In class PILE, I have a private variable: CARD storage[MAX_CARD]. I am trying to initialize the deck to 52 cards of spades, hearts, diamonds and clubs. Below is a substandard for-loop.
for(int i=0;i
This for-loop achieves the results, but not in order of suit, then rank. I have tried to construct a for-loop that will do exactly that, but I am having some problems.

The trick here is to use nested for-loops. Here is an example:

class Card
	enum suit {spade,hearts,diamonds,club,end_suit};
	enum rank {ace,one,two,three,four,five,six,seven,eight,nine,ten,
	Card (suit st = end_suit,rank rk=end_rank): suit_(st),rank_(rk)

	const Card &operator = (suit s, rank r)
		suit_ = s;
		rank_ = r;
		return *this;

	rank Rank() const { return rank_;}
	suit Suit() const { return suit;}
	suit suit_;
	rank rank_;

class Deck 
		for(Card::suit s = spade; s < end_suit; ++s)
			for(Card::rank r = ace; r < end_rank; ++r)
				card_[s][r] = Card(s,r);

	// ... other methods..
	// ...

	Card card_[Card::suit_end][Card::rank_end];
Here I define a two-dimensional array and fill it with data according to the suit, rank. I also defined a copy assignment operator for the class Card so I can write the for-loop more elegantly. Also, class Card needs a default constructor because it will be used in an array.
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date