Skip to content
Justice Tech School

Custom Sorting

Pass a comparator or lambda to sort.

Example
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

int main() {
  std::vector<std::string> w = {"pear", "fig", "apple"};
  std::sort(w.begin(), w.end(), [](auto &a, auto &b) { return a.size() < b.size(); });
  for (auto &s : w) std::cout << s << " ";
  std::cout << "\n";
  return 0;
}

Result

fig pear apple 

Exercise

Comparator.

sort(b, e, )

Quiz Test

What does the comparator return?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.