Lesson 22 of 24

Templates: Generic Code

9 min 35 XP

A template lets one function or class work with any type. vector<int> and vector<string> are templates themselves!

Example: edit me and press Run

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.

Challenge

+35 XP

Write template <typename T> class Stack with push, pop, top and empty, backed by a vector<T>. In main(), push n numbers and pop them all while printing, then do the same with three words. Input: 3 1 2 3 red green blue Output: 3 2 1 blue green red

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.