why my code hava an error : Line 18: invalid use of non-static member function ?


  • 0
    W
    class Solution {
    public:
    bool c(Interval i1, Interval i2) {
    	return i1.start < i2.start;
    }
    
        vector<Interval> merge(vector<Interval>& intervals) {
        	//sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){return a.start < b.start;}); //OK
            sort(intervals.begin(), intervals.end(), c);   // why?? Line 18: invalid use of non-static member function
        	vector<Interval> res;
        	int end = 0;
        	for (auto &i : intervals) {
        		if (res.empty() || i.start > end) {
        			res.push_back(i);
        			end = i.end;
        		}
        		else if (i.end <= end) {
        			continue;
        		}
        		else {
        			res.back().end = i.end;
        			end = i.end;
        		}
        	}
        	return res;
        }
    };
    

  • 0
    S

    your non-static class function Solution::c() is actually taking three parameters: Interval * this, Interval i1 and Interval i2;

    std::sort function is expecting a function that takes only two parameters Interval i1 and Interval i2.

    To solve this problem, declare the function Solution::c() as a static function in a class, in which way there is no parameters Interval *this.

    Regards,


  • 0
    W
    This post is deleted!

Log in to reply
 

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