STL

In this lesson, we'll learn about the C++ STL sorting library and how to leverage it to perform custom sorting.

C++ STL

Here’s what we will be doing when we have to sort an array or vector.

Array

Press + to interact
#include <bits/stdc++.h>
using namespace std;
int main() {
int N = 8;
int arr[N] = {5, 3, 6, 4, 8, 1, 7, 2};
sort(arr, arr + N);
for(int i = 0; i < N; i++)
cout << arr[i] << " ";
return 0;
}

Vector #

Press + to interact
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> vect{5, 3, 6, 4, 8, 1, 7, 2};
sort(vect.begin(), vect.end());
for(int i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}

The actual sorting algorithm used will depend on the language but these are generally faster sorting algorithms of the order O(NlogN)O(NlogN).


Custom comparator

The sort function sorts the integers in non-decreasing order. For other data types, default comparison is used. For example:

  • float - same as int.
  • pair<first, second> - the first part of the pair is compared first. If they are the same, then the second part is compared.
...