0

I am new to cpp I just saw new way of writing comparator for sorting using this[] so what is the use this here because when i was defining the comparator in normal way ,i was getting the error like this

Edit: error

/code/Solution.cpp:22:52: error: invalid use of non-static member function sort(intervals.begin(),intervals.end(),comp);

bool comp(vector<int>&v1, vector<int>&v2) {
return v1[1] < v2[1];
}

Original and legit way here

class Solution {
public:
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) {
            return a[1] < b[1];
        });
        int prev = INT_MIN;
        int ans = 0;
        for (auto &it : intervals) {
            if (it[0] >= prev) {
                prev = it[1];
            }
            else
                ++ans;
        }
        return ans;
    }
};
akacodes121
  • 129
  • 8
  • 1
    What error were you getting? The `[]` thing is for [lambdas](https://stackoverflow.com/q/7627098/1270789). – Ken Y-N Oct 18 '19 at 08:13
  • 2
    Could you show us the code that is not working and the error message you are getting? Just to mention in passing, your comparator should work with const references. The `[]` thing is called lambda function, an unnamed function object. – ypnos Oct 18 '19 at 08:13
  • I just updated @ypnos – akacodes121 Oct 18 '19 at 08:15
  • Your [`comp()` needs to be static](https://stackoverflow.com/q/1902311/1270789). – Ken Y-N Oct 18 '19 at 08:19

1 Answers1

0

The [] is the beginning of what is called a lambda in C++.

You can read a nicely written answer on what lambdas are here :

What is a lambda expression in C++11?

Also, you haven't provided your original code so I can't point out the mistake. But from the error message, it seems that the function comp you created was inside a class. One way is to make the function global, after which you should be able to pass it comfortably. Another option is to make the function static (which i believe makes sense). You can then pass it sort like this: sort(a.begin(), a.end(), A::comp) where A is class in which you made this function.

Jatin Sharma
  • 331
  • 1
  • 10