Template argument deduction
Exercise: Write a function map(func, vec), where func is any unary function and vec is any vector. Returns a vector obtained from vec by replacing every element x with func(x).
template <typename Func, typename T>
auto map(Func func, const std::vector<T> &vec) {
std::vector<T> result;
for (const auto &x : vec)
result.push_back(func(x));
return result;
}
Usage:
std::vector v{1, 2, 3, 4};
auto v2 = map([](int x) { return x * 2; }, v);