Home > Mobile >  How myCompare() function is working in c sorting program?
How myCompare() function is working in c sorting program?

Time:08-13

How is the myCompare() function working? like what is p1 and what is p2? I want to know what is happening in function (like in debugging).

#include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
using namespace std;

bool myCompare(pair<int, int> p1, pair<int, int> p2){
    return p1.first<p2.first;
}

int main(){
    int arr[]={10,16,7,14,5,3,12,9};
 
    vector <pair <int, int>> v;

    for(int i=0;i<(sizeof(arr)/sizeof(arr[0]));i  ){
        v.push_back(make_pair(arr[i],i));
    }
    for(auto a:v){
        cout<<a.first<<" "<<a.second<<"    ";
    }cout<<endl;

    sort(v.begin(),v.end(),myCompare);

    for(auto a:v){
        cout<<a.first<<" "<<a.second<<"    ";
    }cout<<endl;
}

CodePudding user response:

A sort function typically does a series of comparisons to build a sorted range of given elements. For comparison you can use less than or greater than operator for ascending or descending ordering. You can also define and use a completely unique comparison operator for your interpretation of your data type as long as it satisfies Compare requirements.

A comparison function defines an ordering on a type. It takes two elements as input, and returns a boolean. A comparison function comp must satisfy some rules to define a meaningful ordering (and no UB) such as:

For all a, comp(a,a)==false
If comp(a,b)==true then comp(b,a)==false
if comp(a,b)==true and comp(b,c)==true then comp(a,c)==true

In your example, v is sorted using myCompare function defined as a comparison operator on type pair<int, int>. myCompare only takes the first element of the pair into account, which is perfectly valid and satisfies all the rules for Compare.

CodePudding user response:

The short answer is that:

  1. myCompare tells the std::sort function how to sort integer pairs.
  2. p1 and p2 are the integer pairs to be compared.

Think about it. If you have 2 pairs of integers, say {10, 4} and {20, 2}, how would you know how to sort them?

  • Should {10, 4} come first because 10 < 20?
  • Should {20, 2} come first because 2 < 4?
  • Maybe you want to use both values in your comparison, like (10/4) < (20/2)?

The myCompare function simply describes that the first comparison method should be used, only taking into account the first value of each pair.

So in this example where p1 is {10, 4} and p2 is {20, 2}, myCompare would order them p1, p2 because 10 < 20.

In your main() function, myCompare will be called many times while std::sort sorts through your vector and passes in the 2 integer pairs (as p1 and p2) it is comparing in that moment.

  • Related