Skip to main content

STL for Competitive Programming

Why STL is Essential

The C++ STL provides battle-tested, optimized implementations of common data structures and algorithms. Using STL effectively can be the difference between solving a problem in 5 minutes vs 30 minutes.
The CP Mindset: Don’t implement what STL provides. Know what’s available, know its complexity, and use it without hesitation.

Containers Cheat Sheet

When to Use What


Vector: Your Default Container

Essential Operations

Vector Patterns


Set and Map: Sorted Containers

Set Operations

Map Operations

Multiset (Allows Duplicates)


Priority Queue: Heap

Basic Usage

Pattern: Dijkstra’s Algorithm


Algorithms Header

Sorting

Other Useful Algorithms


String Operations


Pattern Recognition: Choosing the Right Container

Need Fast Lookup?

  • By index → vector
  • By key → unordered_map (O(1)) or map (O(log n))
  • Check existence → set or unordered_set

Need Ordering?

  • Sorted iteration → set, map
  • Quick min/max → priority_queue
  • Find closest → lower_bound, upper_bound

Need Frequency?

  • Count occurrences → map<T, int> or unordered_map<T, int>
  • With removal → multiset (careful with erase!)

Need FIFO/LIFO?

  • Stack → stack or vector
  • Queue → queue or deque
  • Both ends → deque

Common Pitfalls

Pitfall 1: Iterator Invalidation

Pitfall 2: Modifying Map While Iterating

Pitfall 3: Using [] on Non-Existent Key


Key Takeaways

Know Your Complexities

vector O(1) access, set/map O(log n), unordered_* O(1) average.

Use STL Algorithms

sort, lower_bound, unique, accumulate save time and bugs.

Default to Vector

Unless you need specific properties, vector is usually the best choice.

Careful with Erase

Erasing invalidates iterators. Know the patterns.

Next Up

Chapter 4: Prefix Sum & Difference Arrays

Answer range queries in O(1) and apply updates efficiently with these fundamental techniques.