C++, lesson 14
C++'s signature strength is generic programming: writing code once and using it with many types, at full speed. The standard library's containers and algorithms, known together as the STL, are built this way, and you can write your own generic code with templates.
Without templates you would write largest once for int, again for double, again for
std::string. A template writes it once, with a placeholder type T:
The compiler deduces T from the arguments and generates a separate, fully typed function
for each type you use. The only requirement is that the code inside makes sense for ; here,
must support . If it doesn't, you get a compile error, never a runtime surprise. Both
arguments must deduce the same , so fails; write
to choose yourself.
2 exercises to try what you just read.
TT<Tlarger(1, 2.5)larger<double>(1, 2.5)TContainers are class templates: std::vector<int> and std::vector<std::string> are two types
stamped out from one blueprint. You can write your own:
That last line uses class template argument deduction (C++17): just as std::vector v{1, 2, 3}
becomes a std::vector<int>, the compiler works out the template argument from the
constructor.
Algorithms don't know about containers. They work on iterator ranges [first, last), and
every container provides begin() and end(). That's why one std::sort serves vectors,
arrays and strings, and why algorithms return iterators (positions) rather than indexes.
<algorithm> and <numeric> hold dozens of tested building blocks. Each name states the intent
more clearly than a raw loop does:
Two details to remember: std::accumulate's result has the type of its starting value, so sum
doubles with 0.0, not 0. And algorithms that "find" something return end() when they come
up empty, so check before dereferencing.
A lambda can use variables from the surrounding code if you list them in the capture brackets:
[limit] copies limit into the lambda, [&total] refers to total itself, and [=] or [&]
capture everything used, by copy or by reference.
Templates, iterators, algorithms and lambdas together let you write code that is generic, short and as fast as a hand-tuned loop.
Write a function template largest that takes a const std::vector<T>& (never empty) and
returns its largest element using only < on the elements. A hidden main reads three lists, of
integers, decimals and words, and calls your template once for each type.
Input: a count followed by that many integers, a count and that many decimals, a count and that many words. Output:
Only write the template; the #include lines and main are provided. Bonus: try
std::max_element, which returns an iterator to the largest element.
Read exam scores (whole numbers from 0 to 100) until the input ends; there is at least one. Using algorithms rather than hand-written loops for the calculations, print:
Count: <n>Average: <x>, with two decimals (std::accumulate)Passed: <n>, scores of at least 50 (std::count_if)Range: <min>-<max> (std::minmax_element)Curved: <scores>, every score plus 5 but never above 100, in the original order, separated
by spaces (std::transform and std::min)template <typename T>
T larger(const T& a, const T& b) {
return a < b ? b : a;
}
larger(3, 9); // T is int
larger(2.5, 1.0); // T is double
larger(std::string{"kiwi"}, std::string{"fig"}); // T is std::stringtemplate <typename T>
class Box {
public:
explicit Box(T value) : value_{std::move(value)} {}
const T& get() const { return value_; }
private:
T value_;
};
Box<int> a{42};
Box b{std::string{"hat"}}; // C++17 deduces Box<std::string> from the argumentstd::vector<int> v{4, 8, 15, 16, 23, 42};
int total = std::accumulate(v.begin(), v.end(), 0); // 108
auto evens = std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }); // 4
auto big = std::find_if(v.begin(), v.end(), [](int x) { return x > 20; }); // points at 23
auto [lo, hi] = std::minmax_element(v.begin(), v.end()); // iterators to 4 and 42
bool all_pos = std::all_of(v.begin(), v.end(), [](int x) { return x > 0; }); // true
std::vector<int> doubled(v.size());
std::transform(v.begin(), v.end(), doubled.begin(), [](int x) { return x * 2; });int limit{50};
auto passed = std::count_if(scores.begin(), scores.end(),
[limit](int s) { return s >= limit; });Input:
3
4 9 2
2
1.5 -0.5
3
pear apple zebra
Output:
int: 9
double: 1.5
string: zebraInput:
45 78 92 50 98
Output:
Count: 5
Average: 72.60
Passed: 4
Range: 45-98
Curved: 50 83 97 55 100