8.x — Chapter 8 summary and quiz
Quick review#
std::vector<T>is a list that can grow. Usepush_backto add.- Indexes start at 0. The last one is
size() - 1. for (const auto& x : list)visits every item.std::array<T, N>is a fixed-size list.- Strings have tools:
length,substr,find,+. std::map<Key, Value>looks up values by key.
Pick an answer. You find out right away if it is right.
For std::vector<int> v { 4, 8, 15 }; what is v[1]?
Indexes start at 0, so v[1] is the second item.
Which adds 16 to the end of v?
push_back adds to the end and grows the vector. v[3] would be out of bounds.
What does a std::map<std::string, int> store?
A map links each key (here a std::string) to a value (here an int).
What does this print?
std::vector<int> v { 5, 10, 15, 20 };std::cout << v[1] + v[3];30. v[1] is 10 and v[3] is 20.
What's wrong here?
std::vector<int> v { 1, 2, 3 };for (std::size_t i { 0 }; i <= v.size(); ++i) std::cout << v[i];i <= v.size() goes one step too far: it tries v[3], which doesn't exist. Use i < v.size().
Write a function that takes a std::vector<int> and returns the biggest number in it. (Assume the list is not empty.)
int biggest(const std::vector<int>& v){ int best { v[0] }; for (int x : v) { if (x > best) best = x; } return best;}(There's also a ready-made tool: *std::max_element(v.begin(), v.end()).)
Write a program that reads a word and prints it backwards.
#include <iostream>#include <string> int main(){ std::string word {}; std::cin >> word; for (int i { static_cast<int>(word.length()) - 1 }; i >= 0; --i) { std::cout << word[i]; } std::cout << '\n'; return 0;}Or with <algorithm>: std::reverse(word.begin(), word.end());
Tip: press ← / → to move between lessons, / to search.