11.7. A single-pass solution¶
Although this code works, it is not as efficient as it could be. Every
time it calls how_many, 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:
std::vector<std::size_t> histogram (static_cast<std::size_t>(upper_bound) + 1, 0);
for (const int& value: numbers) {
++histogram[static_cast<std::size_t>(value)];
}
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.
Not initializing our data to 0 is another form of undefined behavior and
a common error.
The loop assumes every value is between zero and upper_bound inclusive.
Check that condition before indexing when the values come from untrusted input.
The loop has the same assumption as before:
the index position of the histogram vector is the value in the
numbers vector.
Try this!
Encapsulate this code in a function called histogram
that takes a vector and the range of values in the vector (in this case
0 through 9), and that returns a histogram of the values in the vector.
Q1
What happens if you don't initialize a counter?
Q2
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.
-
} return histogram; } -
for (int i = 0; i < range; i++) { -
for (std::size_t i = 0; i < vec.size(); i++) { -
histogram[index]++; -
std::size_t index = i; -
std::size_t index = static_cast<std::size_t>(vec[i]); -
vector<std::size_t> histogram (range); -
vector<std::size_t> histogram (range, 0); -
vector<std::size_t> histogram(const vector<int>& vec, std::size_t range) {