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 67 68 69 70 71 72 73 74 75 76
|
#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
class Invoice
{
public:
Invoice(string description, double price, int quantity) :
description_(description),
price_(price),
quantity_(quantity),
cost_(price * quantity)
{
}
const string& Description() { return description_; }
double Price() { return price_; }
int Quantity() { return quantity_; }
double Cost() const { return cost_; }
private:
string description_;
double price_;
int quantity_;
double cost_; // Total cost
};
struct InvoiceSorter
{
bool operator()(const Invoice& a, const Invoice& b) const
{
return a.Cost() < b.Cost();
}
};
void Show(Invoice* arr, int arr_size)
{
for(int i=0; i<arr_size; ++i)
{
Invoice& v = arr[i];
cout << right << setw(15) << v.Description() <<
right << setw(7) << v.Price() << " * " <<
left << setw(5) << v.Quantity() << " $" <<
left << setw(7) << v.Cost() << endl;
}
cout << endl;
}
int main()
{
int NUM_ITEMS = 8;
Invoice invoices[] =
{
{ "Bat", 2.95, 3 },
{ "Baseball", 5.99, 4},
{ "Glove", 2.56, 1},
{ "Hockey Stick", 10.24, 2},
{ "Mask", 4.24, 2},
{ "Hockey Puck", 3.67, 1},
{ "Tennis Racket", 16.42, 2},
{ "Tennis Ball", 0.99, 9}
};
cout << fixed << setprecision(2);
cout << "Before: " << endl;
Show(invoices, NUM_ITEMS);
cout << "After: " << endl;
sort(invoices, invoices + NUM_ITEMS, InvoiceSorter());
Show(invoices, NUM_ITEMS);
return 0;
}
|