#ifndef EX13_7_H #define EX13_7_H #include <iostream> template <typename U> void swap(U& a,U& b) { U temp; temp = a; a = b; b = temp; } template <typename T> void sort(T* a,int size) { int i,j; for (i = 1; i < size; i++) for (j = 0; j < i; j++) if ( a[i] < a[j] ) swap(a[i],a[j]); } template <typename V> void arrayPrint(const V* a,int size) { int i; for (i = 0; i < size; i++) std::cout << a[i] << std::endl; std::cout << std::endl; } #endif |
#include "ex13-7.h" #include <iostream> using namespace std; class Fraction { private: int numer,denom; public: Fraction(int n = 0, int d = 1) : numer(n), denom(d) {} void assign(int n, int d) { numer = n; denom = d; } int operator<(Fraction& f); friend ostream& operator<<(ostream& s, const Fraction& f); }; int Fraction::operator<(Fraction& f) { return (static_cast<float>(numer)/denom < static_cast<float>(f.numer)/f.denom); } ostream& operator<<(ostream& s,const Fraction& f) { s << f.numer << '/' << f.denom; return s; } class Card { protected: int pips; int suit; public: Card(int n = 0) : pips(n % 13), suit(n / 13) { } bool operator<(const Card& c) const { return pips < c.pips; } static const string PipsName[13]; static const string SuitName[4]; friend ostream& operator<<(ostream&, const Card&); }; const string Card::PipsName[13] = {"two","three","four","five", "six","seven","eight","nine","ten","jack","queen","king","ace"}; const string Card::SuitName[4] = {"clubs","diamonds","hearts","spades"}; ostream& operator<<(ostream& out, const Card& card) { out << Card::PipsName[card.pips] << " of " << Card::SuitName[card.suit]; return out; } class PinocleCard : public Card { public: PinocleCard(int n = 0) : Card(n) { pips = n % 6 + 7; suit = n / 2 % 4; } int operator<(PinocleCard&); }; int PinocleCard::operator<(PinocleCard& c) { if (pips != 8 && c.pips != 8) return (pips < c.pips); else if (pips == 8 && c.pips != 12) return 0; else if (c.pips == 8 && pips != 12) return 1; else return 0; } int main() { // array of int int a1[5] = { 3, 5, 1, 9, 94}; arrayPrint(a1,5); sort(a1,5); arrayPrint(a1,5); // array of double double a2[4] = { 3.7, 1.5, -1.1,.9}; arrayPrint(a2,4); sort(a2,4); arrayPrint(a2,4); // array of char char a3[4] = {"hey"}; arrayPrint(a3,3); sort(a3,3); arrayPrint(a3,3); // array of Fractions Fraction a4[4] {{2,3},{1,2},{3,4},{5,9}}; arrayPrint(a4,4); sort(a4,4); arrayPrint(a4,4); // array of cards Card a5[4] = {47,23,43,1}; arrayPrint(a5,4); sort(a5,4); arrayPrint(a5,4); // array of PinocleCards PinocleCard a6[6] = {32,18,41,10,13,27}; arrayPrint(a6,6); sort(a6,6); arrayPrint(a6,6); } |