Custom Comparators: for sorting(vectors,etc.)

Revision en2, by anveshgandotra_, 2025-01-13 14:24:09

Custom Comparator for Sorting

The jist of building the custom comparator function:

  • return FALSE: if swap required i.e. before element is actually supposed to be after
  • return TRUE: in case order is correct

Method 1: Lambda function

void solve(){
    vector<pair<int,int>> vec1;
    vector<pair<int,int>> vec2;
    for(int i=1;i<=4;i++){
        vec1.push_back(make_pair(i,5-i+1));
        vec2.push_back(make_pair(i,5-i+1));
    }
    for(int i=1;i<=4;i++){
        vec1.push_back({1,i});
        vec2.push_back({1,i});
    }
    //default sort()
    cout<<"default sort: ascending according to both ele.first and ele.second: "<<endl;
    sort(vec1.begin(),vec1.end());
    for(auto ele:vec1){
        cout<<"("<<ele.first<<","<<ele.second<<");";
    }
    cout<<endl;
    //custom sort()
    cout<<"custom sort: descending according to  ele.first and ascending acc to ele.second: "<<endl;
    sort(vec2.begin(),vec2.end(),[&](pair<int,int> before,pair<int,int> after){
        //return FALSE: if swap required i.e. before ele is actually supposed to be after
        //return TRUE: in case order is correct
        if(before.first==after.first){
            return before.second<after.second;
            //if before.second is smaller it should come earlier on(ascending order)
        }
        return before.first>after.first;
        //before.first is bigger it should come earlier on(desc order)
    });
    for(auto ele:vec2){
        cout<<"("<<ele.first<<","<<ele.second<<");";
    }
    cout<<endl;
    
}

Your Output

default sort: ascending according to both ele.first and ele.second: (1,1);(1,2);(1,3);(1,4);(1,5);(2,4);(3,3);(4,2); custom sort: descending according to ele.first and ascending acc to ele.second: (4,2);(3,3);(2,4);(1,1);(1,2);(1,3);(1,4);(1,5);

Method 2: Separately defined function

static bool cmp(pair<int,int> before,pair<int,int> after){
        //return FALSE: if swap required i.e. before ele is actually supposed to be after
        //return TRUE: in case order is correct
        if(before.first==after.first){
            return before.second<after.second;
            //if before.second is smaller it should come earlier on(ascending order)
        }
        return before.first>after.first;
        //before.first is bigger it should come earlier on(desc order)
}
void solve(){
        //......
        sort(vec2.begin(),vec2.end(),cmp);
        //.......
}
Tags custom comparator, cpp, vector

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English anveshgandotra_ 2025-01-13 14:24:09 0 (published)
en1 English anveshgandotra_ 2025-01-13 14:23:38 2597 Initial revision (saved to drafts)