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个回答

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

 #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 cmp1(node a, node b)
{
    if (a.x != b.x)
    {
        return a.x > b.x;
    }
    else
    {
        return a.y > b.y;
    }
}

int main()
{
    int array1[5] = {1, 2, 3, 4, 5};
    sort(array1, array1+5);
    for (int i = 0; i < 5; i++)
    {
        cout << array1[i] << " ";
    }
    cout << endl;
    sort(array1, array1+5, cmp);
    for (int i = 0; i < 5; i++)
    {
        cout << array1[i] << " ";
    }
    cout << endl;
    vector <node> stu;
    node n1, n2, n3;
    stu.push_back(n1);
    stu.push_back(n2);
    stu.push_back(n3);
    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(), cmp1);

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

1、sort()函数不能分别重载函数
2、把
bool cmp(int a, int b)//double also works
{
return a > b;
}
改为
bool cmp1(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;
}
}
改为
bool cmp2(node a, node b)
{
if (a.x != b.x)
{
return a.x > b.x;
}
else
{
return a.y > b.y;
}
}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问