Step 7
Loops
Repeat work for every item in a vector: add up totals and find the closest ball.
Do it for every item
A range for loop runs its block once for each item in a vector, with the loop variable set to that item:
std::vector<std::string> balls = {"red", "green", "blue"};
for (std::string color : balls) {
std::cout << color << " ball" << "\n";
}
To add things up, create a variable before the loop and update it inside. total += d is short for total = total + d:
double total = 0;
for (double d : {0.25, 0.5, 0.25}) {
total += d;
}
std::cout << total << "\n"; // 1
When you need the index as well as the item, count with the classic for loop. Its three parts are where to start, when to keep going, and what to do after each pass (i++ adds 1 to i):
for (std::size_t i = 0; i < balls.size(); i++) {
std::cout << i << " " << balls[i] << "\n";
}
std::size_t is the type C++ uses for sizes and indexes: a whole number that's never negative. The loop counts i through 0, 1, …, size − 1, exactly the indexes of the vector.
The best so far
To find the smallest value, remember the best one seen so far and replace it whenever you find a better one:
double best = values[0];
for (double v : values) {
if (v < best) {
best = v;
}
}
Robots do this constantly: the closest ball, the shortest path, the pose with the smallest error.
Your task
- Write
total(distances)so it returns the sum of a vector of numbers, using a loop. An empty vector adds up to 0. - Write
closest_ball(names, distances).names[i]is a ball's colour anddistances[i]is how far that ball is from the gripper. Return the name of the closest ball. If two are equally close, return the one that comes first.