Templates and the standard library

Writing code once for many types with templates, and using the standard library's vector, map and algorithms instead of writing your own.

About 7 hours of study

Learning objectives

Lessons

  1. 1

    Templates

    Write a function or class once for any type: the compiler makes an int version, a string version, and so on.

  2. 2

    The standard library: vector, string, map and sort

    Ready-made containers and algorithms: a vector grows by itself, a map keeps keys sorted, sort works on any range.

Module practice

Module quiz

1. For largest(4, 7), with template <typename T> T largest(T a, T b), what is T?
2. vector<int> v = {5, 1}; v.push_back(3); What is v.size()?
3. In what order does a range-for over map<string, int> visit the entries?
4. Are Box<int> and Box<string> the same class?
5. map<string, int> m; is empty. What does m["x"]++; do?
6. What must a type support to be used with a sorted-list template that compares items with <?
7. You keep a reference to v[0] and then call v.push_back many times. Why is the reference dangerous?

‹ Inheritance and polymorphismExceptions and design ›