[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指针, 当然类型不对


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值