Algorithms with Lambdas

Lambdas really shine together with the STL algorithms. You tell the algorithm what to do with a tiny lambda.

Sorting your own way

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<string> words = {"banana", "kiwi", "apple", "fig"};
    sort(words.begin(), words.end(), [](const string& a, const string& b) {
        return a.length() < b.length();          // shortest first
    });
    for (const string& w : words) cout << w << " ";
    cout << "\n";
    return 0;
}

Output

fig kiwi apple banana 

The lambda answers one question: “should a come before b?”

Counting and finding with a rule

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> temps = {18, 25, 31, 22, 35, 29};
    int hot = count_if(temps.begin(), temps.end(), [](int t) { return t > 28; });
    cout << hot << " hot days\n";

    auto it = find_if(temps.begin(), temps.end(), [](int t) { return t > 30; });
    if (it != temps.end()) {
        cout << "First day over 30: " << *it << "\n";
    }
    return 0;
}

Output

3 hot days
First day over 30: 31

Changing every item: transform and for_each

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> prices = {10, 20, 30};
    vector<int> withTax(prices.size());
    transform(prices.begin(), prices.end(), withTax.begin(), [](int p) { return p + p / 10; });
    for_each(withTax.begin(), withTax.end(), [](int p) { cout << p << " "; });
    cout << "\n";
    return 0;
}

Output

11 22 33 

Removing items that match a rule

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
    v.erase(remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }), v.end());
    for (int x : v) cout << x << " ";
    cout << "\n";
    return 0;
}

Output

1 3 5 7 

Remember: remove_if only moves the unwanted items to the end; erase then cuts them off. Always use the two together. This pattern is called the erase-remove idiom.

HOME LABS COMMUNITY DASHBOARD