Templates, lambdas and STL algorithms
You have used std::vector<int> and std::vector<std::string> without anyone writing two versions of vector. The reason is templates: code written once with a type as a parameter, which the compiler instantiates for each concrete type you use. Today you will learn to write your own generic functions and classes, and you will see two allies that make them much more powerful: lambdas, small functions you write right where you need them, and the STL algorithms, which sort, search, count and transform any sequence without you writing the loop.
Function and class templates
A function template is declared with template <typename T> before the function. The compiler deduces T from the arguments: largest(3, 7) uses int and largest(2.5, 1.5) uses double. If the two arguments have different types, deduction fails and you must give the type by hand, as in largest<double>(3, 7.5). Class templates work the same way, and since C++17 the compiler also deduces the type on construction (CTAD): Box b{42}; creates a Box<int>. An important requirement: the type used must support the operations the template employs. If largest uses >, the type must have that operator; otherwise the error appears at instantiation and is usually long and confusing, but read only the first line.
#include <iostream>
#include <string>
#include <utility>
template <typename T>
T largest(const T& a, const T& b) {
return (a > b) ? a : b;
}
template <typename T>
class Box {
public:
explicit Box(T value) : value_{std::move(value)} {}
const T& get() const { return value_; }
void set(T value) { value_ = std::move(value); }
private:
T value_;
};
int main() {
std::cout << largest(3, 7) << '\n'; // 7
std::cout << largest(2.5, 1.5) << '\n'; // 2.5
std::cout << largest<double>(3, 7.5) << '\n'; // 7.5
std::cout << largest(std::string{"pear"}, std::string{"apple"}) << '\n'; // pear
Box box{42}; // CTAD: Box<int>
Box<std::string> label{"hi"};
box.set(box.get() + 1);
std::cout << box.get() << ' ' << label.get() << '\n'; // 43 hi
return 0;
}Lambdas
A lambda is a nameless function defined where it is used. Its form is [capture](parameters) { body }. The brackets say which variables from the surroundings it can use: [] nothing, [x] copies x, [&x] uses x by reference, [=] copies everything it uses and [&] takes everything by reference. Beware of capturing by reference a variable that stops existing before the lambda runs: it would be a dangling reference. When in doubt capture by copy. You can store a lambda in a variable with auto, or pass it directly to an algorithm.
Algorithms from <algorithm> and <numeric>
The algorithms work with ranges delimited by two iterators, normally v.begin() and v.end(). The most used: sort orders; count_if counts elements meeting a condition; find_if returns an iterator to the first one that meets it (or end() if there is none); transform applies an operation to each element and writes the result; accumulate (in <numeric>) sums or reduces. They will almost always receive a lambda as the condition. Using algorithms instead of hand-written loops makes code shorter, expresses intent and avoids index errors. Always remember to check that find_if did not return end() before dereferencing the iterator.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> v{5, 2, 8, 1, 9, 3};
std::sort(v.begin(), v.end()); // 1 2 3 5 8 9
std::sort(v.begin(), v.end(), [](int a, int b) { // descending
return a > b;
});
std::sort(v.begin(), v.end()); // back to ascending
int threshold = 4;
auto bigger = std::count_if(v.begin(), v.end(),
[threshold](int x) { return x > threshold; });
std::cout << "bigger than 4: " << bigger << '\n'; // 3 (5, 8, 9)
auto it = std::find_if(v.begin(), v.end(), [](int x) { return x > 6; });
if (it != v.end()) {
std::cout << "first > 6: " << *it << '\n'; // 8
}
std::vector<int> squares(v.size());
std::transform(v.begin(), v.end(), squares.begin(),
[](int x) { return x * x; });
for (int s : squares) {
std::cout << s << ' '; // 1 4 9 25 64 81
}
std::cout << '\n';
int total = std::accumulate(v.begin(), v.end(), 0);
std::cout << "sum = " << total << '\n'; // sum = 28
return 0;
}✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符