Skip to main content

Section 13.6 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 11 in this sample. By starting the loop counter at 1, we know it will be safe to check the previous index:
Listing 13.6.1.
If we want to access the next value at i + 1, we need to make sure our loop stops earlier. Index size() - 1 is the index of the last element. So our loop needs to stop before it gets to that point. The last index the loop iterates on should i = size() - 2 so that when it calculates i + 1 it gets that index.

Checkpoint 13.6.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.
You have attempted of activities on this page.