The STL toolbox for contests

Introduction

You rarely write a sorting routine or a balanced tree in a contest. The C++ Standard Template Library already has them, tested and fast. A handful of tools cover most problems: sort, vector, pair, set, map and lower_bound. Knowing their costs lets you choose the right one in seconds.

This lesson is a short tour. The later lessons use these tools constantly, so it pays to know them well.

How it works

Sorting and pairs

sort(a.begin(), a.end()) sorts in O(n log n). A pair<int, int> holds two values, .first and .second, and pairs compare by first and then by second, so a vector<pair<int, int>> sorts correctly with no extra code. Store {value, original index} pairs when you need to remember where each value came from.

set and map

A set<int> keeps distinct values in sorted order. insert, erase and count cost O(log n). Building a set from a vector removes duplicates, so set.size() is the number of distinct values. A map<int, int> stores a value for each key; freq[x]++ counts how often x appears, because a missing key starts at 0.

NeedToolCost per operation
order the itemssortO(n log n) in total
distinct valuessetO(log n)
count by keymapO(log n)
first value at least xlower_boundO(log n)

lower_bound

On a sorted vector, lower_bound(a.begin(), a.end(), x) returns an iterator to the first element that is at least x. Subtract a.begin() to get the index. If every element is smaller, it returns a.end(), which is index n. upper_bound finds the first element strictly greater than x, so upper_bound - lower_bound counts how often x appears.

Pick by the limits. A map with 10⁵ operations is fine; one with 10⁸ is not. If the keys are small integers, a plain array or vector is faster still.

Example

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

int main() {
    vector<int> a = {40, 10, 30, 10, 20, 30, 10};
    vector<int> sorted = a;
    sort(sorted.begin(), sorted.end());
    cout << "sorted: ";
    for (int x : sorted) cout << x << " ";
    cout << "\n";

    set<int> distinct(a.begin(), a.end());
    cout << "distinct values: " << distinct.size() << "\n";

    map<int, int> freq;
    for (int x : a) freq[x]++;
    for (auto& kv : freq) cout << kv.first << " appears " << kv.second << " times\n";

    int pos = lower_bound(sorted.begin(), sorted.end(), 25) - sorted.begin();
    cout << "first value that is at least 25 is at index " << pos << ": " << sorted[pos] << "\n";
    return 0;
}
Open in compiler

The program sorts a list, counts its distinct values with a set, counts how often each value appears with a map, and finds the first value that is at least 25 with lower_bound.

Line by line

  • sorted is a copy of a; sort puts it in increasing order.
  • set<int> distinct(a.begin(), a.end()) builds the set in one go. Equal values collapse into one.
  • freq[x]++ adds 1 to the count for x; the for loop over freq visits the keys in increasing order.
  • lower_bound(...) - sorted.begin() turns the iterator into an index.

Expected result

sorted: 10 10 10 20 30 30 40 
distinct values: 4
10 appears 3 times
20 appears 1 times
30 appears 2 times
40 appears 1 times
first value that is at least 25 is at index 4: 30

In the real world

Sorting and searching are everywhere: ordering search results, de-duplicating records, counting events per user, finding the first price above a threshold. The same containers appear in production C++ code. Choosing between a sorted vector (cheap and cache friendly), a set (changing data) and a map (counting) is an everyday decision.

Common mistakes

  • Calling lower_bound on a vector that is not sorted. The result is meaningless.
  • Reading a[pos] when lower_bound returned a.end(), which is index n and out of range.
  • Using map when an array is enough, which is slower by a large constant.
  • Writing a comparator that returns true for equal items, which breaks sort.
  • Expecting set to keep duplicates. Use multiset for that.

Best practices

  • Sort first when the order does not matter; many hard problems get easy after a sort.
  • Use vector by default and reach for set or map only when you need sorted order with changes.
  • Check whether lower_bound found something before using it.
  • Count with map<key, int> and the freq[x]++ idiom.
  • Remember the costs: sort O(n log n), set and map O(log n) per operation.

Summary

sort, pair, set, map and lower_bound cover a huge share of contest problems. Sorting makes order work for you, set removes duplicates, map counts, and lower_bound finds a position in a sorted vector in O(log n). Know the costs and you will choose the right tool without thinking.

Quick check

1. What does lower_bound(a.begin(), a.end(), x) return on a sorted vector?
2. How do you count the distinct values in a vector a?
3. A map<int, int> freq has no key 7. What does freq[7]++ do?
4. How do vector<pair<int, int>> items sort by default?

Key takeaways

  • sort is O(n log n) and is often the first step of a solution
  • set and map keep their keys sorted and cost O(log n) per operation
  • lower_bound answers where does x belong in a sorted vector in O(log n)
  • The right container often turns an O(n²) idea into O(n log n)

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.