#include #include #include using namespace std; template void kswap(T &a, T &b){ T temp = a; a = b; b = temp; } template class kpair{ public: T first; S second; kpair(); kpair(T a, S b):first(a), second(b){} }; // to implement outside of a class. template kpair::kpair():first(0),second(0){} class Jabberwocky{ public: string name; int feet; bool firebreathing; bool flying; Jabberwocky(){} Jabberwocky(string n, int f, bool fire, bool fly):name(n),feet(f),firebreathing(fire), flying(fly){} /* obsolete if using the comparator function object bool operator < (Jabberwocky &J){ // sort on number of feet return feet < J.feet; // sort on firebreathing //return (!firebreathing && J.firebreathing); // sort on flying //return (!flying && J.flying); } */ friend ostream & operator<<(ostream &o, Jabberwocky &J); }; ostream & operator<<(ostream &o, Jabberwocky &J){ o << endl; o << J.name << " is a " << endl; o << J.feet << " footed " << endl; if(J.firebreathing) o << "Firebreathing" << endl; else o << "Non-flamable" << endl; if(J.flying) o << "Flying Jabberwocky " << endl; else o << "Land-locked Jabberwocky " << endl; return o; o << endl; } struct comp{ string compare; comp(string c):compare(c){} bool operator()(const Jabberwocky &a,const Jabberwocky &b)const{ // least to greatest if(compare == "feets") return a.feet < b.feet; else if(compare == "flying") return !a.flying && b.flying; else if(compare == "fire") return !a.firebreathing && b.firebreathing; } }; void main(){ // change kpair to pair, see what happens kpair p(3,3.14159); cout << p.first << " " << p.second << endl; int x = 3, y = 7; // change kswap to swap, see what happens. kswap(x,y); cout << x << " " << y << endl; string s("one"), v("two"); kswap(s, v); cout << s << " " << v << endl; // sort Jabberwockies Jabberwocky j[5]; Jabberwocky Linda("Linda",2, 1, 0); j[0] = Linda; Jabberwocky John("John", 4, 0, 1); j[1] = John; Jabberwocky Matt("Matt", 2, 1, 1); j[2] = Matt; Jabberwocky Joyce("Joyce", 2, 0, 1); j[3] = Joyce; Jabberwocky Keith("Keith", 4, 1, 1); j[4] = Keith; sort(j, j+5, comp("flying")); for(int i = 0; i < 5; i++) cout << j[i]; }