Postponing an sqrt computation when comparing distances
In this example, we will show you how to use a proxy object in order to postpone, or even avoid, using the computationally heavy std::sqrt() method when comparing the distance between two dimensional points.
A simple two-dimensional point class
Let's start with a simple point class in 2D. It has x and y coordinates and a member function, which calculates the distance to another point:
class Point{
public:
Point(float x, float y) : x_{x}, y_{y} {}
auto distance(const Point& p) const {
auto dist_sqrd = std::pow(x_-p.x_, 2) + std::pow(y_-p.y_, 2)
return std::sqrt(dist_sqrd);
}
private:
float x_{};
float y_{};
};A simple usage example would be as follows:
auto target = Point{3, 5};
auto a = Point{6, 9};
auto b = Point{7, 4};
auto nearest_target =
target.distance(a) < target.distance(b) ?
a : b;
auto a_to_b_distance = a.distance(b);
| ![]() Distances from two arbitrary points to target... |
