sort, count_if and find_if from <algorithm>, driven by small lambdas that can capture variables.
C++ · beginner · 8 min · 10 steps · free
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {5, 2, 8, 1};
sort(v.begin(), v.end()); // ascending
sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); // with a lambda: descending
int evens = count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
int limit = 4;
auto big = find_if(v.begin(), v.end(), [limit](int x) { return x < limit; }); // captures limit
int firstSmall = *big;
cout << v[0] << " " << evens << " " << firstSmall << endl;
return 0;
}v is created on the stack with the value [5, 2, 8, 1].limit is created on the stack with the value 4.firstSmall is created on the stack with the value 2.8 2 2.0.Answer: Nothing. Empty brackets.
Answer: A comparator returning a > b. Pass a comparison.