Accessing a Container's Elements in Reverse : list reverse « list « C++ Tutorial






#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>

using namespace std;

template <class ForwIter>
void print(ForwIter first, ForwIter last, const char* title)
{
   cout << title << endl;
   while ( first != last)
      cout << *first++ << '\t';
   cout << endl;
}

class Card
{
   public:
   enum Suit { spades, clubs, hearts, diamonds };

   Card( int value = 1, Suit suit = spades );
   // value - 1 = Ace, 2-10, 11 = Jack, 12 = Queen, 13 = King

   bool operator<( const Card& rhs ) const;

   void print() const;

   int suit() const;
   int value() const;

   private:
   int value_;
   Suit suit_;
}; 

inline
Card::Card( int value, Suit suit )
   : value_( value ), suit_( suit )
{} // empty

inline
bool Card::operator<( const Card& rhs ) const
{ return value() < rhs.value(); }

void Card::print() const
{
   if( value() >= 2 && value() <= 10 )
      cout << value();
   else
      switch( value() )
      {
         case  1: cout << "Ace"; break;
         case 11: cout << "Jack"; break;
         case 12: cout << "Queen"; break;
         case 13: cout << "King"; break;
      };

   cout << " of ";
   switch( suit() )
   {
      case spades: cout << "spades"; break;
      case clubs: cout << "clubs"; break;
      case diamonds: cout << "diamonds"; break;
      case hearts: cout << "hearts"; break;
   default: cout << "unknown suit"; break;
     }
    cout << endl;
}

inline
int Card::suit() const
{ return suit_; }

inline
int Card::value() const
{ return value_; }

int main( )
{ 
   list<Card> hand;

   hand.push_back( Card( 12, Card::hearts ) );
   hand.push_back( Card( 6, Card::clubs ) );
   hand.push_back( Card( 12, Card::diamonds ) );
   hand.push_back( Card( 1, Card::spades ) );
   hand.push_back( Card( 11, Card::clubs ) );

   hand.sort();
   for_each( hand.begin(), hand.end(), mem_fun_ref( &Card::print ) );

   for_each( hand.rbegin(), hand.rend(), mem_fun_ref( &Card::print ) );
}








17.13.list reverse
17.13.1.Reversing Elements in a list
17.13.2.Accessing a Container's Elements in Reverse
17.13.3.Use reverse function on list