Alex Ed
Alex Ed

Reputation: 41

How to sort class objects array using the sort() in C++

I was doing one programming problem where it is required to sort the class objects.

So, i used sort() to sort the array of objects but i couldn't do it, i read somewhere it requires lambda expression to that, but i don't know about them yet.

So, if you can help me with this question with some explanation of lambda expression it would be wonderful.

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

class CallLog{
    public:
    string pno;
    int dur;
    string da;
    void setpno(string p_no) {pno = p_no;}
    void setdur(int d) {dur = d;}
    void setda(string dsa) {da = dsa;}
    string getpno() {return pno;}
    int getdur() {return dur;}
    string getda() {return da;}
};

int main() {
    int n;
    cin >> n;
    CallLog arr[n];
    for(int i = 0; i < n; i++) {
        string pno;
        int dur;
        string da;
        cin >> pno >> dur >> da;
        arr[i].setpno(pno);
        arr[i].setdur(dur);
        arr[i].setda(da);
    }
    sort(arr, arr+n, "what labmda expression to write?" );
    for(int i = 0; i < n; i++) {
        cout << "DialledNumber : " << arr[i].getpno() << ", Duration : " << arr[i].getdur() << ", Date : " << arr[i].getda() << "\n";
    }
}

I want to sort these objects with respect to the int dur.

Upvotes: 0

Views: 797

Answers (2)

dilem-ma-vi
dilem-ma-vi

Reputation: 33

The predefined STL function objects, located in the FUNCTIONAL header file. There are function objects corresponding to all the major C++ operators. In the table, the letter T indicates any class, either user-written or a basic type. The variables x and y represent objects of class T passed to the function object as arguments. "bool = greater(T, T) x > y bool = less(T, T) x < y". Also if you want you can write your own function objects.

Upvotes: 0

Ivan
Ivan

Reputation: 1455

Sorting is about comparing elements and knowing which one is "lower" than other one (ie, if I sort {5,3,1} into {1,3,5}, it is because 1 is lower than 3 and 3 is lower than 5)

So, it depends on what kind of logic you want to follow for your sorting algorithm (you could, for example, sort them by their member int dur). sort() uses the < operator to sort, so you have two options:

  1. Overload the < operator as shown here <= I suggest you to do this, for example:
bool operator<(CallLog a, CallLog b)
{
    return a.dur < b.dur;
}
  1. You can actually use a lambda, as in this example <= notice that even if it shows how to do it using lambdas, it also shows that writing the < operator would be way nicer. Also here, there's an easy-to-read example on how to sort passing a function to sort().

Upvotes: 1

Related Questions