Skip to main content

Section 13.8 Accessing Consecutive Elements

Sometimes while traversing, we want to compare one element with another. For instance, if we want to see if values in a vector are in order we can check each value to make sure it is larger than the previous one. For example, in a four item vector, if the 2nd element is larger than the 1st, and the 3rd is larger than the 2nd, and the 4th is larger than the 3rd, we know that all four elements are in order.
To compare every item with the previous, it is generally easiest to use a counting loop instead of a range-based loop. Our counting variable (typically i) represents “the current index”. Assuming we are counting up, the next lower value, i - 1, would be the “previous index” and the next high value, i + 1, would be “the next index”. Thus vec.at(i) is the “current element”, vec.at(i - 1) is the “previous element” and vec.at(i + 1) is the “next element”.
When using i - 1 or i + 1, we have to adjust our loop to make sure we do not go out of bounds on the vector. If we start counting from 0, and try to access i - 1, we would end up with index -1, which would cause an exception. So we should start our loop at index 1. Pay special attention to lines 10 and 12 in this sample. By starting the loop counter at 1, we know it will be safe to check the previous index:
Listing 13.8.1.

Note 13.8.1.

The local variables current and previous are just for clarity. We could shorten lines 13-15 to just:
if (vec.at(i) < vec.at(i - 1)) {
However, giving names to vec.at(i) and vec.at(i - 1) can make the code easier to read and understand. It also allows us to easily check those values in the debugger. Furthermore, simple variables like this are the kind of thing a compiler will generally optimize away, so there is likely no performance penalty.
If we want to access the next value at i + 1, we need to make sure our loop stops in time to avoid accessing the item at index size(). (Index size() - 1 is the index of the last element!) So the last value i reaches should i = size() - 2. That way, when we calculate i + 1, we get size() - 1, which is the last valid index.

Checkpoint 13.8.1.

Construct a block of code that compares the “current” element with the “next” element at each iteration to determine if a vector is in order. Assume vec has already been declared and initialized.
Be careful that your index does not go out of bounds at the end of the vector.
Hint.
< size - 1 means the highest value the loop counter can reach is size() - 2.
< size - 2 means the highest value the loop counter can reach is size() - 3.
You have attempted of activities on this page.