Sorting by Functions in C++
Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in C++.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main() {
std::vector<std::string> fruits = {"peach", "banana", "kiwi"};
// We implement a comparison function for string lengths.
auto lenCmp = [](const std::string& a, const std::string& b) {
return a.length() < b.length();
};
// Now we can call std::sort with this custom comparison function
// to sort fruits by name length.
std::sort(fruits.begin(), fruits.end(), lenCmp);
for (const auto& fruit : fruits) {
std::cout << fruit << " ";
}
std::cout << std::endl;
// We can use the same technique to sort a vector of
// values that aren't built-in types.
struct Person {
std::string name;
int age;
};
std::vector<Person> people = {
{"Jax", 37},
{"TJ", 25},
{"Alex", 72}
};
// Sort people by age using std::sort.
std::sort(people.begin(), people.end(),
[](const Person& a, const Person& b) {
return a.age < b.age;
});
for (const auto& person : people) {
std::cout << "{" << person.name << " " << person.age << "} ";
}
std::cout << std::endl;
return 0;
}
In this C++ version, we use std::sort
from the <algorithm>
header instead of slices.SortFunc
. The comparison functions are implemented as lambda expressions.
For sorting the fruits
vector, we define a lenCmp
lambda that compares string lengths. We then pass this to std::sort
along with the iterators for the beginning and end of the vector.
For the Person
struct, we sort directly within the std::sort
call using an inline lambda expression that compares the age
field.
Note that in C++, we need to explicitly print each element of the sorted containers. We use range-based for loops for this purpose.
To compile and run this program:
$ g++ -std=c++11 sorting_by_functions.cpp -o sorting_by_functions
$ ./sorting_by_functions
kiwi peach banana
{TJ 25} {Jax 37} {Alex 72}
This example demonstrates how to use custom sorting functions in C++ to sort both built-in types (strings) and user-defined types (Person structs) based on specific criteria.