A question about the usage of sort in C++

  • 0

    Hi I am very new to the 'sort' function in C++. And I got a question when I was trying to solve this problem, my question is if I need to use sort with my own function as below, why do I have to declare the compare function as 'static' here(If not using static, it will have non-static function calling error)......Thanks in advance.

    class Solution {
          static  bool compare(const Interval itv1, const Interval itv2){
                         return (itv1.start < itv2.start);
        bool canAttendMeetings(vector<Interval>& intervals) {
            vector<Interval> itv = intervals;
            for(int i=1;i<intervals.size();i++){
                if (intervals[i].start<intervals[i-1].end)
                    return false;
            return true;

  • 1

    In C++, pointers to non-static function must be passed (or called) using a class pointer beforehand. It is because non-static members are associated with class instances.

    Please refer to this page for more details.

  • 0

    You may want to use lambda as your comparator:

            sort(intervals.begin(), intervals.end(),
             [](const Interval& a, const Interval& b) {
                 return a.start < b.start;

  • 0

    got it, thanks man

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.