FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses C++ and STL Essentials

CSE

Progress0 / 6 lessons
  1. 1. What C++ adds over C
  2. 2. References vs pointers
  3. 3. vector and why it beats raw arrays
  4. 4. map and set with real complexity numbers
  5. 5. Sorting with comparators
  6. 6. Strings and stringstream

Courses › C++ and STL Essentials

Sorting with comparators

std::sort, lambdas, sorting structs by multiple fields, and the rule your comparator must obey.

11 min read · Lesson 5 of 6 · Pro

sort is already written and it is fast

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

int main() {
    vector<int> v = {5, 2, 9, 1, 7};

    sort(v.begin(), v.end());
    for (int x : v) cout << x << " ";
    cout << "\n";                       // 1 2 5 7 9

    sort(v.begin(), v.end(), greater<int>());
    for (int x : v) cout << x << " ";
    cout << "\n";                       // 9 7 5 2 1
    return 0;
}
The rest of this lesson is Pro

The free lessons of C++ and STL Essentials finish what they start — read those first if you have not. This one goes further, and it is part of the paid half.

A pass opens the paid lessons of every course, the mock test papers and the company-wise series. It ends on its own date; nothing renews by itself.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.