In C++ Std::Sort is an "algorithm", not a function. That is, Std::Sort is a generic function declared as a template.
The use of the comparison function is necessary when there is no intrinsic order to be used when comparing the elements. This intrinsic order would be defined by the operator "<".
In the example below, it is not possible to compare two instances of the Person class: it is not possible to do "if (P1 < P2)" unless the operator for the Person class is written.
The comparison function does not necessarily have to be an "Operator <", any function that takes 2 Person parameters and returns "bool" can be used. In the example below we use the "isAgeLess" function to "compare" two instances of the Person class.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Person
{
string name;
int age;
};
bool isAgeLess(const Person& p1, const Person& p2)
{
return p1.age < p2.age;
}
vector<Person> people
{
{ "Maria", 17 },
{ "Joao", 15 },
{ "Antonio", 53 },
{ "Carlos" , 13 },
};
int main()
{
sort(people.begin(), people.end(), isAgeLess);
cout << "*\n";
for (const auto& p : people)
{
cout << "* nome=" << p.name << "\t idade=" << p.age << '\n';
}
cout << "*\n";
}
Upshot:
*
* nome=Carlos idade=13
* nome=Joao idade=15
* nome=Maria idade=17
* nome=Antonio idade=53
*
In the case, summarized, when the function returns
false
the values are permuted on the vector and it is executed on the vector until it returnstrue
for all elements?– Woss
Does it mean that I can sort a set of integers without the order being ascending or descending? I can define that order?
– Andrey França
@Andrey França: this.
– zentrunix
@Anderson: the comparison function is used in the same way that the "<" operator would be used: if "func(a,b)" returns true, it means that "a < b", if it returns false then it means "a >=b", and these results are used to classify the elements.
– zentrunix