且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[c++]no matching function for call to ‘sort(…)......

更新时间:2022-08-12 18:52:59

【问题】

[c++]no matching function for call to ‘sort(…)......

在做LeetCode的Merge Intervals时用到c++的sort函数,一直出这个错误,甚是郁闷。最后终于找到了问题所在。

【代码】

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

struct Interval {
    int start;
    int end;
    Interval() : start(0), end(0) {}
    Interval(int s, int e) : start(s), end(e) {}
};

class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        int count = intervals.size();
        if(count <= 1){
            return intervals;
        }//if
        // x轴排序
        sort(intervals.begin(),intervals.end(),cmp);
    }
private:
    // 比较函数
    bool cmp(Interval& ina,Interval& inb){
        return ina.start < inb.start;
    }
};


【解决】

cmp函数要定义在类的外面, 或者定义成为static类型

具体:

cmp()

{...}

class Solution

{

...

sort(...);

}

原因:

cmp是定义在一个类中的成员函数。开始的时候老是报错:no matching function for call to 'sort(...), <unresolved overloaded function type>'。后来我把该成员定义成静态函数,问题解决。原因可能和类成员函数的函数原型有关。所有成员函数都有一个隐含的指针参数,即this。这就和sort需要的comp函数原型不一致了,所以就报错了。而static函数就没有这个隐含参数了

如果类中有个cmp函数,调用时,类型就多了个this指针, 当然类型不对