Skills101

C++ Programming · Lesson 7 of 9 · Updated ·

STL Algorithms and Lambdas — sort, binary search, accumulate and Competitive Programming Tips

<algorithm> and <numeric> give you tested, optimised building blocks. Using them makes code shorter and less buggy — and interviewers like it.

STL containers and the costs of their operations — algorithms work on any of them through iterators

1. Sorting and lambdas

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

int main() {
    vector<int> v = {5, 2, 9, 1, 7};
    sort(v.begin(), v.end());                       // ascending
    for (int x : v) cout << x << " ";
    cout << "\n";
    sort(v.begin(), v.end(), greater<int>());       // descending
    cout << v[0] << "\n";

    vector<pair<string, int>> s = {{"Ravi", 74}, {"Asha", 92}, {"Neha", 92}};
    sort(s.begin(), s.end(), [](const auto &a, const auto &b) {
        if (a.second != b.second) return a.second > b.second;   // marks high → low
        return a.first < b.first;                              // then name A → Z
    });
    for (auto &[n, m] : s) cout << n << ":" << m << " ";
    cout << "\n";
    return 0;
}
1 2 5 7 9
9
Asha:92 Neha:92 Ravi:74

A lambda [](params) { body } is an unnamed function you write right where you need it. [&] captures outside variables by reference.

2. Binary search on sorted data

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

int main() {
    vector<int> v = {10, 20, 20, 20, 30, 40};
    cout << binary_search(v.begin(), v.end(), 30) << "\n";
    auto lo = lower_bound(v.begin(), v.end(), 20);   // first element >= 20
    auto hi = upper_bound(v.begin(), v.end(), 20);   // first element  > 20
    cout << (lo - v.begin()) << " " << (hi - v.begin()) << " count=" << (hi - lo) << "\n";
    return 0;
}
1
1 4 count=3

lower_bound / upper_bound are O(log n) and solve many "first position", "count in range" problems.

3. Handy algorithms

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

int main() {
    vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
    cout << accumulate(v.begin(), v.end(), 0) << " ";          // sum
    cout << *max_element(v.begin(), v.end()) << " ";
    cout << count(v.begin(), v.end(), 1) << "\n";
    reverse(v.begin(), v.end());
    cout << v[0] << "\n";
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());               // remove duplicates (after sort)
    for (int x : v) cout << x << " ";
    cout << "\n";
    return 0;
}
31 9 2
6
1 2 3 4 5 6 9

accumulate(…, 0) adds in int. For large sums use 0LL so the total is a long long.

4. All permutations

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

int main() {
    string s = "abc";
    do {
        cout << s << " ";
    } while (next_permutation(s.begin(), s.end()));
    cout << "\n";
    return 0;
}
abc acb bac bca cab cba

Start from the sorted order to get every permutation.

5. Competitive programming setup

#include <bits/stdc++.h>       // GCC-only: includes everything (fine for contests, not for real projects)
using namespace std;
using ll = long long;

int main() {
    ios::sync_with_stdio(false);   // fast input/output
    cin.tie(nullptr);
    int t;
    cin >> t;
    while (t--) {
        // solve one test case
    }
}

Tips: use long long when values can exceed about 2 × 10⁹; prefer "\n" over endl in big outputs; read constraints first to choose the complexity (10⁵ elements → O(n log n) is fine, O(n²) is not).

Practise on our coding problems — C++ is supported by the judge.

Common mistakes

  • Calling unique without sorting first.
  • binary_search / lower_bound on unsorted data.
  • A comparator that isn't a strict ordering (using <=) — it can crash sort.

Quick recap

  • sort with greater<> or a lambda comparator.
  • lower_bound / upper_bound / binary_search on sorted ranges.
  • accumulate, max_element, count, reverse, unique, next_permutation.
  • Contest setup: fast I/O, long long, check constraints.

Practice what you learned

📝 Quiz: STL Algorithms5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →