Std::Sort with comparison function

Asked

Viewed 2,985 times

3

Studying a little about the STL I came across the function std::sort which may receive a comparison function.

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );

How does this comparison function work? And how is it used?

1 answer

3


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 returns true for all elements?

  • 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: this.

  • @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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.