Size and the Last Element
Often you don't know how many elements a vector has. Maybe another part of the program filled it, or the number of elements changes while the program runs (you'll learn to add and remove elements soon). This is how you find out:
std::vector<std::string> students = {"Jennifer", "Boris", "Nancy", "David", "Ava"};
std::cout << students.size() << std::endl;This prints:
5size() is a method: a command that belongs to a value, here to the vector. You write it after the variable's name, separated by a dot. This is called dot notation. So students.size() means “the size of the vector students”. Using a method is called calling it. A method's name is always followed by parentheses, even when there is nothing in them. Vectors have more methods, and you'll meet a few more of them in this lesson.
The method size() gives you a number, so you can store it in an int variable, calculate with it or print it with a label:
int numberOfStudents = students.size();
std::cout << "Students: " << numberOfStudents << std::endl;This prints:
Students: 5If you forget the parentheses and write int numberOfStudents = students.size;, the program doesn't compile:
main.cpp:7:37: error: reference to non-static member function must be called; did you mean to call it with no arguments?The message says that the method must be called, and asks whether you meant to call it with nothing in the parentheses. Just add ().
With size(), you know where the last element is. Indexes start at 0, so the last index is always one less than the number of elements: a vector of 5 elements has indexes 0, 1, 2, 3 and 4. The last element is therefore at index students.size() - 1:
std::cout << students[students.size() - 1] << std::endl;This prints:
AvaThe program first calculates the index in the square brackets (5 − 1 = 4) and then reads the element at that index. This finds the last element of a vector of any length, even when its length changes. A common mistake is to forget the - 1: students[students.size()] asks for index 5, where there is no element. You'll see what happens then in the next exercise.
Instructions
- 1
Using
size(), print the number of colleagues with a label. The output should include the lineColleagues: 3. - 2
Create a
std::stringvariable namedlastColleagueand store the last element ofcolleaguesin it. Calculate the index withsize() - 1, don't write the number2. - 3
Print
lastColleaguewith a label:Last: Lucy.