Andrew Koenig

Dr. Dobb's Bloggers

How To Represent Boundaries With Pointers

June 25, 2014

Let's continue last week's discussion about the relationship between boundaries and pointers.

Let's continue last week's discussion about the relationship between boundaries and pointers. We had gotten as far as defining two types, which we called pointer and boundary types, with each type having before and after operations. Applying either of these operations to a pointer yields a boundary, and vice versa.

Two weeks ago, we suggested that if lower and upper are boundaries that define a range of elements in a sequence, we can process those elements by writing code along the following lines:

b = lower;
while (b != upper) {
// Process the element immediately to the right of b
++b;
}

As we have already noted, computer hardware normally gives us pointers, not boundaries; C++ reflects this hardware preference. Accordingly, we would like to rewrite this code to use pointers instead of boundaries.

Let's start by defining begin and end as pointers that define the same range as lower and upper. To do so, we will use the convention we established last week, where the pointer that corresponds to a boundary points to the element immediately after the boundary:

The key point in this code is that in the original version, "the element immediately to the right of b" is the same as after(b). Therefore, because begin is after(lower), and p starts out with the same value as begin, the first time through the loop, the element to process is the one to which p points. Once we have made this observation, the rest of the code follows.

In other words, once we have adopted the convention that in order to convert a boundary to a pointer, we move in a particular direction to find the element to which to point (i.e., using after(b) rather than before(b)), we have done all that is necessary to take the symmetric code that uses boundaries and convert it to asymmetric code that uses pointers. The asymmetry comes from the fact that to turn a boundary into a pointer, we must move in one direction or the other.

Next week, we shall explore the effect that this forced asymmetry has on the design of reverse iterators in the C++ standard library.

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task.
However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Video

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!