Competitive programming

Stage 1 · Lesson 4 of 8

Vectors, pairs and sorting

C++ for contests

A vector is a resizable array, the container you will use in almost every problem. A pair holds two values, and compare by the first value and then by the second, so sorting a vector of pairs sorts by one key and keeps a second value, such as the original index, alongside it.

sort runs in O(n log n) and accepts a , a small function (often a , an unnamed inline function) that says which of two elements comes first. Custom orders drive many greedy solutions, so get comfortable writing them.

Common trapwriting a comparator with <= instead of <, which breaks the rules sort relies on and can crash or give nonsense.

A question to check yourself, an AI practice session and 2 cheat sheet entries come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

  • CourseFree
    LearnCpp.com

    LearnCpp.com · Beginner

    Free and thorough: read the chapters on vectors, references, lambdas and the standard library if C++ is new to you

  • BookFree
    Competitive Programmer's Handbook

    Antti Laaksonen · Beginner

    Chapter 1 covers C++ for contests, input and output and working with numbers; Chapter 2 covers complexity

Practise

  • Start with the Introductory Problems section: short tasks that exercise loops, strings and the STL

  • Filter the problem set to rating 800 and solve a few each day to get used to contest input and output

Keep handy

  • Keep it open for exact signatures and complexities of vector, set, map, sort and lower_bound

Also worth your time

Mark this stage as not done?