Postponing sqrt Computations

Learn how to optimize vector length comparisons using a proxy object.

This section will show you how to use a proxy object to postpone, or even avoid, using the computationally heavy std::sqrt() function when comparing the length of two-dimensional vectors.

A simple two-dimensional vector class

Let’s start with a simple two-dimensional vector class. It has xx and yy coordinates and a member function called length() that calculates the distance from the origin to the location (x,y)(x, y). We will call the class Vec2D. Here follows the definition:

Get hands-on with 1200+ tech skills courses.