Reading Elements
Each element of a vector has a position, called its index. Indexes are counted from zero: the first element has index 0, the second 1, the third 2 and so on. You can think of an index as the number of steps from the start of the vector: the first element is right at the start, zero steps away.
std::vector<std::string> resolutions = {"Write a diary", "Take a falconry course", "Learn to juggle"};Here, "Write a diary" has index 0, "Take a falconry course" index 1 and "Learn to juggle" index 2.
To get an element, write its index in square brackets after the vector's name:
std::cout << resolutions[0] << std::endl;
std::cout << resolutions[2] << std::endl;This prints:
Write a diary
Learn to juggleAn element of a vector of texts is an ordinary std::string text. So you can store it in a variable and print it with a label:
std::string firstResolution = resolutions[0];
std::cout << "First: " << firstResolution << std::endl;This prints:
First: Write a diaryWatch out for the most common mistake: because counting starts at zero, the last of three elements has index 2, not 3. You'll soon see what happens when you ask for an index past the end of a vector.
You can't print a whole vector at once with std::cout. If you write std::cout << resolutions << std::endl;, the program doesn't compile:
main.cpp:7:15: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::vector<std::string>' (aka 'std::vector<basic_string<char>>'))The message says that the operator << didn't get values it can work with (its operands): the output (ostream) on one side, a vector on the other. std::cout can print numbers, characters and texts, but not a vector. Below the message, Clang prints a long list of notes (note:) that you can skip. So print a vector element by element:
std::cout << resolutions[0] << ", " << resolutions[1] << ", " << resolutions[2] << std::endl;This prints:
Write a diary, Take a falconry course, Learn to juggleFor a long vector, that would be a lot of typing. In the next lesson, you'll learn loops, which go through all the elements for you.
Instructions
Print the first colleague from the vector colleagues on a line of its own. The output should include the line Peter.
Create a std::string variable named favoriteColleague and store one colleague of your choice in it. Read it from the vector by its index, for example colleagues[2]. Then print the variable with a label, such as Favorite: Lucy.
Finally, print all three colleagues on one line, separated by a comma and a space: Peter, Adam, Lucy.