Search⌘ K

STL

Explore how to apply C++ STL sorting techniques and define custom comparator functions to sort arrays or vectors by various criteria. Learn to implement sorting that handles odd and even integers differently, enhancing your skills for competitive programming challenges.

C++ STL

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

Array

C++
#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 #

C++
#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.
...