8.x — Chapter 8 summary and quiz

📘 Chapter 8⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

Quick review#

  • std::vector<T> is a list that can grow. Use push_back to 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.
Quick check

Pick an answer. You find out right away if it is right.

Quick check #1

For std::vector<int> v { 4, 8, 15 }; what is v[1]?

Quick check #2

Which adds 16 to the end of v?

Quick check #3

What does a std::map<std::string, int> store?

Quiz time
Question #1

What does this print?

C++
std::vector<int> v { 5, 10, 15, 20 };std::cout << v[1] + v[3];

30. v[1] is 10 and v[3] is 20.

Question #2

What's wrong here?

C++
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().

Question #3

Write a function that takes a std::vector<int> and returns the biggest number in it. (Assume the list is not empty.)

C++
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()).)

Question #4

Write a program that reads a word and prints it backwards.

C++▶ Run
#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());

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.