Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 10.13 A single-pass solution

Although this code works, it is not as efficient as it could be. Every time it calls howMany, it traverses the entire vector. In this example we have to traverse the vector ten times!
It would be better to make a single pass through the vector. For each value in the vector we could find the corresponding counter and increment it. In other words, we can use the value from the vector as an index into the histogram. Here’s what that looks like:
vector<int> histogram(upperBound, 0);

for (int i = 0; i < numValues; i++) {
  int index = vector[i];
  histogram[index]++;
}
The first line initializes the elements of the histogram to zeroes. That way, when we use the increment operator (++) inside the loop, we know we are starting from zero. Forgetting to initialize counters is a common error.

Checkpoint 10.13.1.

What happens if you don’t initialize a counter?
  • Your code runs without a problem because counters are automatically initialized to zero.
  • Incorrect! Variables are not automatically initialized.
  • Your code might run, but it probably won’t produce the output you desire.
  • Correct! C++ might assign unused memory to the uninitialized variable, which will allow the code to run, but counts may be off.
  • You might get an error for using an uninitialized variable.
  • Correct! Depening on your compiler, you might be lucky enough to get an error message.
  • Your program will crash.
  • Incorrect! You might get a compile error, but your program will not crash.

Checkpoint 10.13.2.

Construct a function called histogram that takes a vector and the range of values in the vector, and that returns a histogram of values in the vector.
You have attempted 1 of 3 activities on this page.