Your goal is to write a function object Min_clamped that can be called as a function taking two arguments and returns the minimum between a member variable "_a" and the minimum of the two arguments. Min_clamped has one constructor:
// test_function_objects.cpp
#include <iostream>
template <class T>
class Min_clamped {
public:
Min_clamped (const T& a = 0) /* complete the code for the constructor */
// complete the class Min_clamped to have a function object
private:
T _a;
};
int main() {
Min_clamped<int> min_0;
std::cout << min_0(-1,-2) << std::endl;
std::cout << min_0(1,2) << std::endl;
Min_clamped<double> min_5(5.0);
std::cout << min_5(-1.5, -2.5) << std::endl;
std::cout << min_5(7.5, 7.0) << std::endl;
}
Your goal for this exercise will be to write a function object that will be used to sort two dimensional points in a vector of points according to their distance to the origin.
The distance to the origin for a point p of coordinates (x,y) is given by Sqrt(x^2 + y^2). The method norm() in the class Point_2d is computing that distance for you.
// test_function_algorithms.cpp
#include <algorithm>
#include <vector>
#include <cmath>
#include <ostream>
class Point_2d {
public:
Point_2d(double x, double y) : x_(x), y_(y) {}
double norm() const { return sqrt(x_*x_ + y_*y_); }
double x() const { return x_; }
double y() const { return y_; }
private:
double x_, y_;
};
std::ostream& operator<< (std::ostream& os, const Point_2d& p)
{
os << "(" << p.x() << ", " << p.y() << ")" << std::endl;
return os;
}
// Function object to compare Point_2d according to their distance
// to the origin.
// Example of use:
// Less_Point_2d less;
// Point_2d p1(1.0, 2.0), p2(2.0, 2.0);
// bool t = less(p1, p2); // t == true;
class Less_Point_2d {
// complete the code to turn this class into a function object
// according to the example above
};
int main()
{
Point_2d p1(0.0, 0.0), p2(1.0, 2.0);
Point_2d p3(2.0, 2.0), p4(1.5, 1.5);
Point_2d p5(0.5, 1.5);
std::vector<Point_2d> v;
v.push_back(p1); v.push_back(p2);
v.push_back(p3); v.push_back(p4);
v.push_back(p5);
Less_Point_2d less;
sort(/* complete the argument of sort() such that v is sorted by dist to origin */);
std::vector<Point_2d>::iterator it;
for (it = v.begin(); it != v.end(); it++)
{
std::cout << *it << std::endl;
}
}