SourcePro : Essential Tools Module User's Guide : Collection Classes : Example Using the Essential Tools Module with the C++ Standard Library
Example Using the Essential Tools Module with the C++ Standard Library
The following example is a complete program that creates a deck of cards and shuffles it. The purpose of the example is to show how the Essential Tools Module template collections can be used in conjunction with the C++ Standard Library. See your C++ Standard Library documentation for more information on the features used in the example.
 
/* Note: This example requires the C++ Standard Library */
#include <iostream>
#include <algorithm>
#include <rw/tvordvec.h>
 
struct Card
{
char rank_;
char suit_;
Card (char r, char s) : rank_ (r), suit_ (s) { }
Card (const Card& ref) : rank_ (ref.rank_), suit_ (ref.suit_) { }
 
bool operator== (const Card& ref) const {
return rank_ == ref.rank_ && suit_ == ref.suit_;
}
 
bool operator< (const Card& ref) const {
return rank_ < ref.rank_;
}
 
// print a card: '3-H' = three of hearts, 'A-S' = ace of spades
friend std::ostream&
operator<< (std::ostream& s, const Card& ref) {
s << ref.rank_ << "-" << ref.suit_;
return s;
}
};
 
struct Deck
{
private:
 
int rank_index_; // indexes into static arrays below
int suit_index_;
 
static const char ranks_ [13];
static const char suits_ [4];
 
public:
 
Deck () : rank_index_ (-1), suit_index_ (-1) { }
 
// generate the next Card
Card operator()() {
rank_index_ = (rank_index_ + 1) % 13;
 
if (rank_index_ == 0)
// cycled through ranks, move on to next suit:
suit_index_ = (suit_index_ + 1) % 4;
 
return Card(ranks_[rank_index_], suits_[suit_index_]);
}
};
 
/* static */
const char Deck::suits_[4] = {
'S', 'H', 'D', 'C'
};
 
/* static */
const char Deck::ranks_[13] = {
'A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'
};
 
int main ()
{
// Essential Tools Module collection:
RWTValOrderedVector<Card> deck;
RWTValOrderedVector<Card>::size_type pos;
 
Card aceOfSpades('A','S');
 
// Use standard library algorithm to generate deck:
generate_n(back_inserter(deck.std()), 52, Deck());
std::cout << std::endl << "The deck has been created" << std::endl;
 
// Use Essential Tools Module member function to find card:
pos = deck.index(aceOfSpades);
std::cout << "The Ace of Spades is at position " << pos+1 << std::endl;
 
// Use standard library algorithm to shuffle deck:
std::random_shuffle(deck.begin(), deck.end());
std::cout << std::endl << "The deck has been shuffled" << std::endl;
 
// Use Essential Tools Module member functions:
pos = deck.index(aceOfSpades);
Card firstCard = deck.first();
 
std::cout << "Now the Ace of Spades is at position " << pos+1
<< std::endl << "and the first card is " << firstCard << std::endl;
 
return 0;
}
Output (will vary because of the shuffle):
 
The deck has been created
The Ace of Spades is at position 1
The deck has been shuffled
Now the Ace of Spades is at position 37
and the first card is Q-D