Vectors
Programming Languages · C++ Loops & Vectors · 10 min
Keep a list of values in a std::vector, grow it, and loop over it.
A list of values
A std::vector holds many values of one type, in order. Add #include <vector> at the top, then put the type in angle brackets:
std::vector<int> scores = {90, 75, 82};
std::cout << scores.size() << "\n"; // 3
.size() tells you how many values are inside.
Create a
std::vector<int>callednumsholding4,8,15and16.Print how many values it holds with
nums.size().
Getting one value
Each value has a position called an index. Counting starts at 0, so the first value is [0]:
std::vector<std::string> pets = {"cat", "dog"};
std::cout << pets[0] << "\n"; // cat
pets[1] = "fish"; // replace dog
Print the first fruit using
fruits[0].Change
fruits[1]to"blueberry", then printfruits[1].
Growing with push_back
Vectors can grow. push_back adds a value to the end:
std::vector<int> nums = {1, 2};
nums.push_back(3); // now {1, 2, 3}
Add
"Cleo"to the end ofguestswithpush_back.Print
guests.size(), then on the next line printguests[2].
Visiting every value
To do something with every value, use a range-based for loop. Read it as "for each n in nums":
std::vector<int> nums = {10, 20};
for (int n : nums) {
std::cout << n << "\n";
}
Each time round, n holds the next value.
Print every value in
numson its own line, using a range-basedforloop.
Put it together: shopping cart
Your cart has three prices. Add one more item, count the items, and add up the bill with a loop and a running total.
Add
15topriceswithpush_back.Print
Items: 4usingprices.size().Add every price to
totalwith a range-basedforloop, then printTotal: 40.