11.9 両世界での最良点
次の例は、一組のトランプを作成し、それを切る完全なプログラムです。この例の目的は、Tools.h++
テンプレートコレクションを標準 C++
ライブラリと共にどのように使用するかを示すことにあります。この例で使用されている機能について詳しくは、標準
C++ ライブラリのマニュアルを参照してください。
/* 注意: この例は、標準 C++ ライブラリが必要です */
#include <iostream.h>
#include <algorithm>
#include <rw/tvordvec.h>
struct Card {
char rank;
char suit;
bool operator==(const Card& c) const
{ return rank == c.rank && suit == c.suit; }
Card() { }
Card(char r, char s) : rank(r), suit(s) { }
// カードを表示: 例・'3-C' = クローバの 3, 'A-S' = スペードのエース
friend ostream& operator<<(ostream& ostr, const Card& c)
{ return (ostr << c.rank << "-" << c.suit << " "); }
};
/*
* 生成クラス - 順番通りにカードを返す
*/
class DeckGen {
int rankIdx; // 以下の静的配列にインデックス付け
int suitIdx;
static const char Ranks[13];
static const char Suits[4];
public:
DeckGen() : rankIdx(-1), suitIdx(-1) { }
// 次のカードを生成する
Card operator()() {
rankIdx = (rankIdx + 1) % 13;
if (rankIdx == 0)
// 列を循環し、次の組に移動する:
suitIdx = (suitIdx + 1) % 4;
return Card(Ranks[rankIdx], Suits[suitIdx]);
}
};
const char DeckGen::Suits[4] = {'S', 'H', 'D', 'C' };
const char DeckGen::Ranks[13] = {'A', '2', '3', '4',
'5', '6', '7', '8',
'9', 'T', 'J', 'Q', 'K' };
int main(){
// Tools.h++ コレクション:
RWTValOrderedVector<Card> deck;
RWTValOrderedVector<Card>::size_type pos;
Card aceOfSpades('A','S');
Card firstCard;
// 標準ライブラリのアルゴリズムを使って、一組のトランプを生成する:
generate_n(back_inserter(deck.std()), 52, DeckGen());
cout << endl << "The deck has been created" << endl;
// Tools.h++ のメンバ関数を使ってカードを探す:
pos = deck.index(aceOfSpades);
cout << "The Ace of Spades is at position " << pos+1 << endl;
// 標準ライブラリのアルゴリズムを使って、一組のトランプを切る:
random_shuffle(deck.begin(), deck.end());
cout << endl << "The deck has been shuffled" << endl;
// Tools.h++ メンバ関数を使う:
pos = deck.index(aceOfSpades);
firstCard = deck.first();
cout << "Now the Ace of Spades is at position " << pos+1
<< endl << "and the first card is " << firstCard << endl;
}
/* 出力 (切った結果によって異なる):
The deck has been created (カードのセットが作成された)
The Ace of Spades is at position 1 (スペードのエースは 1 の場所にある)
The deck has been shuffled (カードがシャッフルされた)
Now the Ace of Spades is at position 37 (スペードのエースは 37 の場所にある)
and the first card is Q-D (初めのカードはダイヤのクイーン)
*/