/* * function-objects-01.cc Standard Library, Funtion objects, exercise 1. */ #include #include #include #include #include using namespace std; template const T& median_of_three(const T& x, const T& y, const T& z) { if ((y <= x && x <= z) || (z <= x && x <= y)) return x; else if ((x <= y && y <= z) || (z <= y && y <= x)) return y; else return z; } template const T& median_of_three_set(const T& x, const T& y, const T& z) { set s{ x, y, z }; return *(++s.begin()); } template struct Median_Of_Three { const T& operator()(const T& x, const T& y, const T& z) const { if ((y <= x && x <= z) || (z <= x && x <= y)) return x; else if ((x <= y && y <= z) || (z <= y && y <= x)) return y; else return z; } }; int main() { cout << "Function:\n"; cout << median_of_three(1, 2, 3) << '\n'; cout << median_of_three(1, 3, 2) << '\n'; cout << median_of_three(2, 1, 3) << '\n'; cout << median_of_three(2, 3, 1) << '\n'; cout << median_of_three(3, 1, 2) << '\n'; cout << median_of_three(3, 2, 1) << '\n'; cout << "Function using set:\n"; cout << median_of_three_set(1, 2, 3) << '\n'; cout << median_of_three_set(1, 3, 2) << '\n'; cout << median_of_three_set(2, 1, 3) << '\n'; cout << median_of_three_set(2, 3, 1) << '\n'; cout << median_of_three_set(3, 1, 2) << '\n'; cout << median_of_three_set(3, 2, 1) << '\n'; cout << "Function object:\n"; cout << Median_Of_Three()(1, 2, 3) << '\n'; cout << Median_Of_Three()(1, 3, 2) << '\n'; cout << Median_Of_Three()(2, 1, 3) << '\n'; cout << Median_Of_Three()(2, 3, 1) << '\n'; cout << Median_Of_Three()(3, 1, 2) << '\n'; cout << Median_Of_Three()(3, 2, 1) << '\n'; return 0; }