C++ examples for Operator:Bit Operator
Use bit field to create class DeckOfCards that represents a deck of playing cards
#include <vector> #include <iostream> #include <iomanip> using namespace std; struct Card //from w w w .jav a2s . co m { unsigned face : 4; // 4 bits; 0-15 unsigned suit : 2; // 2 bits; 0-3 unsigned color : 1; // 1 bit; 0-1 }; class DeckOfCards { public: static const int faces = 13; static const int colors = 2; // black and red static const int numberOfCards = 52; DeckOfCards(); // constructor initializes deck void deal(); // deals cards in deck private: vector< Card > deck; // represents deck of cards }; DeckOfCards::DeckOfCards() { for ( int i = 0; i < numberOfCards; ++i ) { deck[ i ].face = i % faces; // faces in order deck[ i ].suit = i / faces; // suits in order deck[ i ].color = i / ( faces * colors ); // colors in order } } void DeckOfCards::deal() { for ( int k1 = 0, k2 = k1 + numberOfCards / 2; k1 < numberOfCards / 2 - 1; ++k1, ++k2 ) cout << "Card:" << setw( 3 ) << deck[ k1 ].face << " Suit:" << setw( 2 ) << deck[ k1 ].suit << " Color:" << setw( 2 ) << deck[ k1 ].color << " " << "Card:" << setw( 3 ) << deck[ k2 ].face << " Suit:" << setw( 2 ) << deck[ k2 ].suit << " Color:" << setw( 2 ) << deck[ k2 ].color << endl; } int main() { DeckOfCards deckOfCards; // create DeckOfCards object deckOfCards.deal(); // deal the cards in the deck }