Lambdas and algorithms
Short inline functions for sort, count_if and transform.
C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
using namespace std;
int main() {
vector<pair<string, int>> students = {{"Kavin", 72}, {"Divya", 95}, {"Ravi", 60}, {"Meena", 88}};
sort(students.begin(), students.end(), [](const auto &a, const auto &b) {
return a.second > b.second;
});
for (const auto &[name, marks] : students) {
cout << name << " ";
}
cout << "\n";
int passMark = 70;
auto passed = count_if(students.begin(), students.end(), [passMark](const auto &s) {
return s.second >= passMark;
});
cout << passed << "\n";
vector<int> marks;
transform(students.begin(), students.end(), back_inserter(marks), [](const auto &s) { return s.second; });
cout << accumulate(marks.begin(), marks.end(), 0) << "\n";
return 0;
}Output
Divya Meena Kavin Ravi 3 315
| Capture | Meaning |
|---|---|
[] | Uses nothing from outside |
[x] | A copy of x |
[&x] | x itself, so changes are seen outside |
[=] / [&] | Everything used, by copy / by reference |
Prefer naming what you capture, as in [passMark], so a reader can see what the lambda depends on. A lambda that captures by reference must not outlive the variables it refers to.