# Initializing a deck of cards using a for-loop

Question:
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;iThis 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.Answer: The trick here is to use nested for-loops. Here is an example:class Card{public:	enum suit {spade,hearts,diamonds,club,end_suit};	enum rank {ace,one,two,three,four,five,six,seven,eight,nine,ten,			   jack,queen,king,end_rank};	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;}private:	suit suit_;	rank rank_;};class Deck {public:	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..	// ...private:	Card card_[Card::suit_end][Card::rank_end];};Here I define a two-dimensional array and fill it with data accordingto the suit, rank. I also defined a copy assignment operator for theclass Card so I can write the for-loop more elegantly.Also, class Card needs a default constructor because it will be used in anarray..ucca906b079d34c92b808f331044db8c0{padding:0;margin:0;padding-top:1em!important;padding-bottom:1em!important;width:100%;display:block;font-weight:700;background-color:#eaeaea;border:0!important;border-left:4px solid #34495E!important;text-decoration:none}.ucca906b079d34c92b808f331044db8c0:active,.ucca906b079d34c92b808f331044db8c0:hover{opacity:1;transition:opacity .25s;webkit-transition:opacity .25s;text-decoration:none}.ucca906b079d34c92b808f331044db8c0{transition:background-color .25s;webkit-transition:background-color .25s;opacity:1;transition:opacity .25s;webkit-transition:opacity .25s}.ucca906b079d34c92b808f331044db8c0 .ctaText{font-weight:700;color:#464646;text-decoration:none;font-size:16px}.ucca906b079d34c92b808f331044db8c0 .postTitle{color:#000;text-decoration:underline!important;font-size:16px}.ucca906b079d34c92b808f331044db8c0:hover .postTitle{text-decoration:underline!important}See also  Comparing different methods of testing your Infrastructure-as-Code`

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.