#include #include //for the abs that takes and returns an int #include #include #include #include "date.h" #include "sorter2.h" using namespace std; inline bool f(int a, int b) {return abs(a - 1955) < abs(b - 1955);} class closer_int { const int i; public: closer_int(int initial_i): i(initial_i) {} bool operator()(int a, int b) const {return abs(a - i) < abs(b - i);} }; class closer_date { const date d; public: closer_date(const date& initial_d): d(initial_d) {} bool operator()(const date& a, const date& b) const { return abs(a - d) < abs(b - d); } }; template //T must be copy constructable and have binary - class closer { const T t; public: closer(const T& initial_t): t(initial_t) {} bool operator()(const T& a, const T& b) const { return abs(a - t) < abs(b - t); } }; template void print(ITERATOR first, ITERATOR last, char c) { for (; first != last; ++first) { cout << *first << c; } cout << "\n"; } int main() { int a1[] = {1929, 1969, 1776, 2001, 1941}; const size_t n1 = sizeof a1 / sizeof a1[0]; sorter(a1, a1 + n1, f); print(a1, a1 + n1, ' '); closer_int ci(1955); sorter(a1, a1 + n1, ci); print(a1, a1 + n1, ' '); sorter(a1, a1 + n1, closer_int(1955)); //construct an anonymous object print(a1, a1 + n1, ' '); sorter(a1, a1 + n1, closer(1955)); print(a1, a1 + n1, ' '); const date a2[] = { date(date::october, 29, 1929), date(date::july, 20, 1969), date(date::july, 4, 1776), date(date::september, 11, 2001), date(date::december, 7, 1941) }; const size_t n2 = sizeof a2 / sizeof a2[0]; vector v(a2, a2 + n2); sorter(v.begin(), v.end(), closer_date(date(date::july, 12, 1955))); print(v.begin(), v.end(), '\n'); sorter(v.begin(), v.end(), closer(date(date::july, 12, 1955))); print(v.begin(), v.end(), '\n'); return EXIT_SUCCESS; }