Custom comparator function | Cpp

Previously I had struggled with the custom comparator function for sorting. As a result, I could not code my thoughts when solving Djikstra, priority queue or when the problem requires custom sorting. I failed, explored and learned.

This is what i learned, and wanted to share
-> custom sort in increasing or decreasing order
-> sorting on pairs
-> Min and Max Heap
-> ordering in Sets and priorityQueue for user defined data type
-> complex Sorting conditions

Level1 : custom sort in increasing or decreasing order

int32_t main()
{
    vector<int> arr = {7,8,9,1,2,6,4,3};

    auto cmpInc = [](int a, int b)
    {
        return a<b;
    };
    auto cmpDec = [](int a, int b)
    {
        return a>b;
    };

    sort(arr.begin() , arr.end() , cmpInc);     // sorts array in increasing order
    sort(arr.begin() , arr.end() , cmpDec);     // sorts array in decreasing order

    for(auto i : arr)
        cout<<i<<" ";
}

Level 2 : custom Sort on pairs

int32_t main()
{
    vector<pairs<int,int>> arr = {{1,2},{2,2},{8,6},{1,4},{8,2},{3,7},{8,4}};

    auto cmpFirst = [](pair<int,int> a, pair<int,int> b)
    {
        return a.first < b.first;
    };
    auto cmpSecond = [](pair<int,int> a, pair<int,int> b)
    {
        return a.second < b.second;
    }
    auto cmp_FirstInc_SecDec = [](pair<int,int> a, pair<int,int> b)
    {
        if(a.first != b.second)
            return a.first < b.first;
        return a.second > b.second;
    };

    sort(arr.begin() , arr.end() , cmpFirst );          // sorts on first 
    sort(arr.begin() , arr.end() , cmpSecond);          // sorts on second
    sort(arr.begin() , arr.end() , cmp_FirstInc_SecDec);// first sorts on first in Increasing order then sorts on second decreasing order
}

Level 3 : Min and Max Heap

int32_t main()
{
    vector<int> a = {7,8,9,1,2,6,4,3};

    auto cmpForMaxHeap = [](int a, int b)
    {
        return a < b;    // observe the condition carefully, this is reverse to what we have done for sorting array using inbuilt sort
    };
    auto cmpForMinHeap = [](int a, int b)
    {
        return a > b;
    };

    priority_queue<int,vector<int>, decltype(cmpForMaxHeap)> maxHeap(cmpForMaxHeap);
    priority_queue<int,vector<int>, decltype(cmpForMinHeap)> minHeap(cmpForMinHeap);

    for(auto i : a)
        minHeap.push(i),
        maxHeap.push(i);

    cout<<"Printing minHeap\n";
    while(minHeap.size())   cout<<minHeap.top()<<" ", minHeap.pop();

    cout<<"\nPrinting maxHeap\n";
    while(maxHeap.size())   cout<<maxHeap.top()<<" ", maxHeap.pop();
}

level 4 : ordering in Sets and priorityQueue for user defined data type
Level 5 : Complex sorting condition

Define a structure/class named Student, Attributes should be name, marks, rollNumber , enrollment Number;
    name             = name of student
    rollNumber       = roll number of student
    marks            = marks of student
    enrollmentNumber = unique number denoting when the student was enrolled in school
    
-> NOTE: Name rollNumber marks can be same ( two students from different section can have same roll and name)
       : enrollment number will not be given you can use a count(this refers to the unique number then the student first registered in school)
Question : Sort the student according to following rules

  first sort according to marks, stundent with greater marks should come first ( decending order)
  if marks are same then sort according to rollNumber in acending order
  if even marks are same then sort according to name, lexographically
  if even name are same then sort according to enrollment number acending order

  Sample :  name , marks , rollNumber
            "Rohan"   33    2
            "John"    87    11
            "Basu"    24    12
            "Chandu"  94    15
            "Daman"   81    19
            "Seema"   24    15
            "Daman"   81    19

						**OUTPUT**
 Chandu     rollNumber: 15   marks: 94       enrollmentNumber: 4
 John       rollNumber: 11   marks: 87       enrollmentNumber: 2
 Daman      rollNumber: 19   marks: 81       enrollmentNumber: 5
 Daman      rollNumber: 19   marks: 81       enrollmentNumber: 7
 Rohan      rollNumber: 2    marks: 33       enrollmentNumber: 1
 Basu       rollNumber: 12   marks: 24       enrollmentNumber: 3
 Seema      rollNumber: 15   marks: 24       enrollmentNumber: 6

Q1 : Try Solving using custom Sorting
Q2 : Try Solving using PriorityQueue
Q3 : Try Solving using Sets ( since enrollment numbers are gonna be unique )**

Try it on, if you were not able to code, dont worry you can explore this

#include<bits/stdc++.h>
using namespace std;

static int _ct = 0;
struct Student
{
    string name;
    int marks, rollNumber, enrollmentNumber;
    Student(string _name, int _marks, int _rollNumber) : name(_name) , marks(_marks) , rollNumber(_rollNumber) , enrollmentNumber(++_ct){};
    void printStudent()
    {
        cout<<"Name "<<name<<"\t";
        printf("rollNumber: %d \t marks: %d \t enrollmentNumber: %d \n" , rollNumber , marks , enrollmentNumber);
    }
};

int32_t main()
{
    vector<Student> student ={
                        //       name , marks , roll
                        Student("Rohan" , 33 , 2),
                        Student("John" , 87 , 11),
                        Student("Basu" , 24 , 12),
                        Student("Chandu" , 94 , 15),
                        Student("Daman" , 81 , 19),
                        Student("Seema" , 24 , 15),
                        Student("Daman" , 81 , 19),
                        };
    vector<Student> studentList1 = student;
    vector<Student> studentList2 = student;
    vector<Student> studentList3 = student;

// Solution for 1st question
    auto cmp1 = [](const Student &a, const Student &b)
    {
        if(a.marks != b.marks)
            return a.marks > b.marks;
        else if(a.rollNumber != b.rollNumber)
            return a.rollNumber < b.rollNumber;
        else if (a.name != b.name)
            return a.name < b.name;
        else 
            return a.enrollmentNumber < b.enrollmentNumber;
    };

    sort(studentList1.begin() , studentList1.end() , cmp1);

    for(auto i : studentList1)
        i.printStudent();
    
    cout<<endl;

// solution for 2nd Question
    
    auto cmp2 = [](const Student &a, const Student &b)
    {
        if(a.marks != b.marks)
            return a.marks < b.marks;
        else if(a.rollNumber != b.rollNumber)
            return a.rollNumber > b.rollNumber;
        else if (a.name != b.name)
            return a.name > b.name;
        else 
            return a.enrollmentNumber > b.enrollmentNumber;
    };

    priority_queue<Student , vector<Student> , decltype(cmp2)> pq(cmp2);

    for(auto i : studentList2)
        pq.push(i);
    
    for(auto &i : studentList2)
        i = pq.top() , 
        pq.pop();
    
    for(auto i :studentList2)
        i.printStudent();

    cout<<endl;

// Solution 3  using sets , we can use sets beacause enrollment numbers are different

    set<Student , decltype(cmp1)> Set(cmp1);
    for(auto i:studentList3)
        Set.insert(i);

    for(auto i : Set)
        i.printStudent();
}

Still having doubts ?
Fail - explore - learn - share


BFS problems

  1. Flood Fill: https://leetcode.com/problems/flood-fill/
  2. Number of Islands: https://leetcode.com/problems/number-of-islands/
  3. Word Ladder I: https://leetcode.com/problems/word-ladder/
  4. Word Ladder II: https://leetcode.com/problems/word-ladder-ii/
  5. Evaluate Division: https://leetcode.com/problems/evaluate-division/
  6. Get Watched Videos by Your Friends: https://leetcode.com/problems/get-watched-videos-by-your-friends/
  7. Cut Off Trees for Golf Event: https://leetcode.com/problems/cut-off-trees-for-golf-event/
  8. 0-1 matrix https://leetcode.com/problems/01-matrix/
  9. As far from land as possible https://leetcode.com/problems/as-far-from-land-as-possible/
  10. Rotting oranges https://leetcode.com/problems/rotting-oranges/
  11. Shortest path in binary matrix https://leetcode.com/problems/shortest-path-in-binary-matrix/

DFS problems

  1. Number of Islands: https://leetcode.com/problems/number-of-islands/
  2. Flood Fill: https://leetcode.com/problems/flood-fill/
  3. Longest Increasing Path in a Matrix: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
  4. Evaluate Division: https://leetcode.com/problems/evaluate-division/
  5. Robot Room Cleaner: https://leetcode.com/problems/robot-room-cleaner/
  6. Most Stones Removed with Same Row or Column: https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/
  7. Reconstruct Itinerary: https://leetcode.com/problems/reconstruct-itinerary/
  8. Tree Diameter: https://leetcode.com/problems/tree-diameter/
  9. Accounts Merge: https://leetcode.com/problems/accounts-merge/
  10. Employee importance https://leetcode.com/problems/employee-importance/
  11. Find the town judge https://leetcode.com/problems/find-the-town-judge/

Connected components problems

  1. Number of Provinces: https://leetcode.com/problems/number-of-provinces/
  2. Number of Connected Components in an Undirected Graph: https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
  3. Number of Operations to Make Network Connected: https://leetcode.com/problems/number-of-operations-to-make-network-connected/
  4. Accounts Merge: https://leetcode.com/problems/accounts-merge/
  5. Critical Connections in a Network: https://leetcode.com/problems/critical-connections-in-a-network/
  6. Surrounded regions: https://leetcode.com/problems/surrounded-regions/
  7. Number of enclaves: https://leetcode.com/problems/number-of-enclaves/
  8. shortest time needed to inform all the employees: https://leetcode.com/problems/time-needed-to-inform-all-employees/

Island Variant

  1. Number of closed island https://leetcode.com/problems/number-of-closed-islands/
  2. Number of islands https://leetcode.com/problems/number-of-islands/
  3. Keys and rooms https://leetcode.com/problems/keys-and-rooms/
  4. Max area of island https://leetcode.com/problems/max-area-of-island/
  5. flood fill: https://leetcode.com/problems/flood-fill/
  6. coloring a border: https://leetcode.com/problems/coloring-a-border/

Dijkstra's problems

  1. Path With Maximum Minimum Valued: https://leetcode.com/problems/path-with-maximum-minimum-value/
  2. Network delay time: https://leetcode.com/problems/network-delay-time/
  3. Path with Maximum Probability: https://leetcode.com/problems/path-with-maximum-probability/
  4. Path With Minimum Effort: https://leetcode.com/problems/path-with-minimum-effort/
  5. Cheapest Flights Within K Stops: https://leetcode.com/problems/cheapest-flights-within-k-stops/

Union Find problems

  1. Number of Islands: https://leetcode.com/problems/number-of-islands/
  2. Largest Component Size by Common Factor: https://leetcode.com/problems/largest-component-size-by-common-factor/
  3. Most Stones Removed with Same Row or Column: https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/
  4. Number of Connected Components in an Undirected Graph: https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
  5. Friend circles: https://leetcode.com/problems/friend-circles/
  6. Redundant connection: https://leetcode.com/problems/redundant-connection/
  7. Most stones removed with same row or columns: https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/
  8. Number of opertions to make network connected: https://leetcode.com/problems/number-of-operations-to-make-network-connected/
  9. Satisfiability of equality equations: https://leetcode.com/problems/satisfiability-of-equality-equations/
  10. Account merge: https://leetcode.com/problems/accounts-merge/
  11. Connecting cities with mimimum cost: https://leetcode.com/problems/connecting-cities-with-minimum-cost/

Minimum Spanning Tree problems

  1. Connecting Cities With Minimum Cost: https://leetcode.com/problems/connecting-cities-with-minimum-cost/
  2. Min Cost to Connect All Points: https://leetcode.com/problems/min-cost-to-connect-all-points/
  3. Optimize water distributions in village: https://leetcode.com/problems/optimize-water-distribution-in-a-village/

Topological sort problems

  1. Course Schedule : https://leetcode.com/problems/course-schedule/
  2. Course Schedule II: https://leetcode.com/problems/course-schedule-ii/
  3. Sequence Reconstruction: https://leetcode.com/problems/sequence-reconstruction/
  4. Alien Dictionary: https://leetcode.com/problems/alien-dictionary/solution/

Floyd Warshall problems

  1. Find the City With the Smallest Number of Neighbors at a Threshold Distance: https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/
  2. Network delay time: https://leetcode.com/problems/network-delay-time/

Bellman Ford problems

  1. Network delay time: https://leetcode.com/problems/network-delay-time/

Finding bridges/Strongly connected components

  1. Critical connections in a network: https://leetcode.com/problems/critical-connections-in-a-network/

Dynamic programming

Longest Increasing Subsequence variants:

  1. longest-increasing-subsequence: https://leetcode.com/problems/longest-increasing-subsequence/
  2. largest-divisible-subset: https://leetcode.com/problems/largest-divisible-subset/
  3. russian-doll-envelopes: https://leetcode.com/problems/russian-doll-envelopes/
  4. maximum-length-of-pair-chain: https://leetcode.com/problems/maximum-length-of-pair-chain/
  5. number-of-longest-increasing-subsequence: https://leetcode.com/problems/number-of-longest-increasing-subsequence/
  6. delete-and-earn: https://leetcode.com/problems/delete-and-earn/
  7. longest-string-chain: https://leetcode.com/problems/longest-string-chain/

Partition Subset:

  1. partition-equal-subset-sum: https://leetcode.com/problems/partition-equal-subset-sum/
  2. last-stone-weight-ii: https://leetcode.com/problems/last-stone-weight-ii/

BitMasking:

  1. partition-to-k-equal-sum-subsets: https://leetcode.com/problems/partition-to-k-equal-sum-subsets/

Longest Common Subsequence Variant:

  1. longest-common-subsequence: https://leetcode.com/problems/longest-common-subsequence/
  2. edit-distance: https://leetcode.com/problems/edit-distance/
  3. distinct-subsequences: https://leetcode.com/problems/distinct-subsequences/
  4. minimum-ascii-delete-sum-for-two-strings: https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/

Palindrome:

  1. palindrome-partitioning-ii: https://leetcode.com/problems/palindrome-partitioning-ii/
  2. palindromic-substrings: https://leetcode.com/problems/palindromic-substrings/

Coin Change variant:

  1. coin-change: https://leetcode.com/problems/coin-change/
  2. coin-change-2: https://leetcode.com/problems/coin-change-2/
  3. combination-sum-iv: https://leetcode.com/problems/combination-sum-iv/
  4. perfect-squares: https://leetcode.com/problems/perfect-squares/
  5. minimum-cost-for-tickets: https://leetcode.com/problems/minimum-cost-for-tickets/

Matrix multiplication variant:

  1. minimum-score-triangulation-of-polygon: https://leetcode.com/problems/minimum-score-triangulation-of-polygon/
  2. minimum-cost-tree-from-leaf-values: https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/
  3. burst-balloons: https://leetcode.com/problems/burst-balloons/

Matrix/2D Array:

  1. matrix-block-sum: https://leetcode.com/problems/matrix-block-sum/
  2. range-sum-query-2d-immutable: https://leetcode.com/problems/range-sum-query-2d-immutable/
  3. dungeon-game: https://leetcode.com/problems/dungeon-game/
  4. triangle: https://leetcode.com/problems/triangle/
  5. maximal-square: https://leetcode.com/problems/maximal-square/
  6. minimum-falling-path-sum: https://leetcode.com/problems/minimum-falling-path-sum/

Hash + DP:

  1. target-sum: https://leetcode.com/problems/target-sum/
  2. longest-arithmetic-sequence: https://leetcode.com/problems/longest-arithmetic-sequence/
  3. longest-arithmetic-subsequence-of-given-difference: https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/
  4. maximum-product-of-splitted-binary-tree: https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/

State machine:

  1. best-time-to-buy-and-sell-stock: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
  2. best-time-to-buy-and-sell-stock-ii: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
  3. best-time-to-buy-and-sell-stock-iii: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
  4. best-time-to-buy-and-sell-stock-iv: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
  5. best-time-to-buy-and-sell-stock-with-cooldown: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
  6. best-time-to-buy-and-sell-stock-with-transaction-fee: best-time-to-buy-and-sell-stock-with-transaction-fee/

Depth First Search + DP:

  1. out-of-boundary-paths: https://leetcode.com/problems/out-of-boundary-paths/
  2. knight-probability-in-chessboard: https://leetcode.com/problems/knight-probability-in-chessboard/

Minimax DP:

  1. predict-the-winner: https://leetcode.com/problems/predict-the-winner/
  2. stone-game: https://leetcode.com/problems/stone-game/

Misc:

  1. greatest-sum-divisible-by-three: https://leetcode.com/problems/greatest-sum-divisible-by-three/
  2. decode-ways: https://leetcode.com/problems/decode-ways/
  3. perfect-squares: https://leetcode.com/problems/perfect-squares/
  4. count-numbers-with-unique-digits: https://leetcode.com/problems/count-numbers-with-unique-digits/
  5. longest-turbulent-subarray: https://leetcode.com/problems/longest-turbulent-subarray/
  6. number-of-dice-rolls-with-target-sum: https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/
Comments (8)