Summary
In this lesson, you learned that:
- A vector stores several values of the same type, its elements, in one variable, in a fixed order. It needs
#include <vector>. The type of the elements goes in angle brackets:std::vector<int> scores = {85, 92, 78};orstd::vector<std::string> names = {"Anna", "Tom"};.std::vector<int> points;is an empty vector. - Each element has an index, counted from 0.
names[0]reads the first element,names[1] = "Lucy";changes the second one. An element behaves like a variable of its type, soscores[0] += 1;works too. - You can't print a whole vector with
std::cout. Print it element by element. - A method is a command that belongs to a value. It's written after a dot and is always followed by parentheses.
names.size()gives you the number of elements. The last element is at indexnames.size() - 1. - Square brackets don't check the index: an index outside the vector reads a meaningless value, or the program crashes.
names.at(5)checks the index, and when it's outside the vector, it stops the program with anout_of_rangeerror. push_back()adds an element to the end of a vector.pop_back()removes the last element and doesn't give anything back, so read an element you need before removing it.- A vector can contain other vectors, called nested vectors:
std::vector<std::vector<std::string>> teams.teams[1][0]is the first element of the second inner vector. - A
std::stringtext is a sequence of characters of typechar. You read a character withtext[0]ortext.at(0)and get the number of characters withtext.size()ortext.length(). A character is written in single quotes:'A'. Letters with accents take up twochars, so write the texts you work with character by character without accents.
In the next lesson, on loops, you'll learn to repeat code, for example to go through all the elements of a vector one by one, however many there are. But first, practice what you know on the readings of a thermometer.
Instructions
- 1
The last reading,
99, is a thermometer error. Remove it fromtemperatureswithpop_back(), and then add the correct value25to the end of the vector withpush_back(). - 2
Print the first temperature, the last temperature and the number of readings, so that the output includes the line
First: 18, last: 25, readings: 5. Find the last temperature withsize() - 1. - 3
Below that, write a condition: if the last temperature is higher than the first one, print
Getting warmer, otherwise printGetting colder. (Once this step passes, try changing the correct value from25to15and see what the program prints.)