1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
template<typename T, typename S> void mySort( vector<T> &V, S T::*p, bool forward = true )
{
if ( forward ) sort( V.begin(), V.end(), [p]( T a, T b ){ return a.*p < b.*p; } );
else sort( V.begin(), V.end(), [p]( T a, T b ){ return a.*p > b.*p; } );
}
template<typename T, typename S> void myFSort( vector<T> &V, S (T::*p)(), bool forward = true )
{
if ( forward ) sort( V.begin(), V.end(), [p]( T a, T b ){ return (a.*p)() < (b.*p)(); } );
else sort( V.begin(), V.end(), [p]( T a, T b ){ return (a.*p)() > (b.*p)(); } );
}
class Laptop
{
string ID;
string name;
int quantity;
double price;
public:
Laptop( string ID, string name, int quantity, double price ) : ID(ID), name(name), quantity(quantity), price(price) {}
string getID(){ return ID; }
string getName(){ return name; }
int getQuantity(){ return quantity; }
double getPrice(){ return price; }
friend ostream & operator << ( ostream &out, const Laptop &L )
{
return out << L.ID << " " << setw(12) << L.name << " " << setw(3) << L.quantity << " " << setw(10) << L.price;
}
};
int main()
{
vector<Laptop> V = { { "ABC", "Dell" , 10, 440.00 },
{ "DEF", "Armageddon", 20, 830.50 },
{ "GEH", "Bother" , 5, 299.99 },
{ "IJK", "Lynx" , 12, 599.99 } };
cout << "Original:\n";
for ( auto &L : V ) cout << L << '\n';
cout << "\nSorted by name:\n";
myFSort( V, &Laptop::getName );
for ( auto &L : V ) cout << L << '\n';
cout << "\nSorted backwards by price:\n";
myFSort( V, &Laptop::getPrice, false );
for ( auto &L : V ) cout << L << '\n';
cout << "\nSorted by quantity:\n";
myFSort( V, &Laptop::getQuantity );
for ( auto &L : V ) cout << L << '\n';
}
| |