yuAriellexi 2018-09-06 13:04 采纳率: 100%
浏览 1001
已采纳

Sort错误使用,no matching function, c++

#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::sort;

struct node
{
    int x, y;
};


bool cmp(int a, int b)//double also works
{
    return a > b;
}

bool cmp(node a, node b)
{
    if (a.x != b.x)
    {
        return a.x > b.x;
    }
    else
    {
        return a.y > b.y;
    }
}

int main()
{
    int array[5] = {1, 2, 3, 4, 5};
    sort(array, array+5);
    for (int i = 0; i < 5; i++)
    {
        cout << array[i];
    }

    sort(array, array+5, cmp);
    for (int i = 0; i < 5; i++)
    {
        cout << array[i];
    }

    vector <node> stu;
    stu[0].x = 2;
    stu[0].y = 1;
    stu[1].x = 2;
    stu[1].y = 3;
    stu[2].x = 4;
    stu[2].y = 0;
    sort(stu.begin(), stu.end(), cmp);

    for (int i = 0; i < 3; i++)
    {
        cout << stu[i].x << " " << stu[i].y << endl;
    }
}

error: no matching function for call to 'sort'
sort(array, array+5, cmp);
error: no matching function for call to 'sort'
sort(stu.begin(), stu.end(), cmp);

这段代码报错
为什么会错,sort也可以用于int类型数组呀

  • 写回答

3条回答 默认 最新

  • threenewbee 2018-09-06 13:18
    关注

    几个问题:
    (1)array是关键字,修改为array1
    (2)cmp具有函数重载,然而sort不能认函数重载,所以必须分开来。将另一个定义为cmp1
    (3)vector stu;这里需要添加3个元素,才能用下标0 1 2访问。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵