Step 6
Vectors
Keep many values in one std::vector, read items by index and add new ones.
Many values under one name
A std::vector holds several values of one type, in order. The type of the items goes in angle brackets:
std::vector<std::string> balls = {"red", "green", "blue"};
std::vector<double> angles = {0.0, 0.5, 1.2, -0.3};
Each item has a position called its index, counting from 0: balls[0] is "red" and balls[2] is "blue". balls.front() and balls.back() are the first and last items.
C++ doesn't check balls[5]: reading past the end gives garbage or crashes the program. balls.at(5) checks, and stops the program with an std::out_of_range error instead. Use .at() while you're unsure of an index.
Working with vectors
balls.size()is the number of items, 3.balls.push_back("yellow")adds an item to the end. It changes the vector itself.std::ranges::count(balls, "red"), from#include <algorithm>, counts how many items equal"red". Zero means it isn't there.return {a, b};builds and returns a new vector from its items, when the function's return type is a vector.
std::vector<std::string> balls = {"red", "green"};
balls.push_back("blue");
std::cout << balls.size() << " " << balls.back() << "\n"; // 3 blue
std::cout << balls doesn't compile: print the items one at a time. The next step's loops make that easy.
Robots keep vectors everywhere: the four joint angles of the arm, the balls on the table, the points along a path.
Your task
- Write
first_and_last(items)so it returns a new vector holding the first and the last item ofitems. For{"red", "green", "blue"}it returns{"red", "blue"}. - Write
add_ball(balls, color). Ifcolorisn't inballsyet, add it to the end. Either way, returnballs.