使用vector.sort()无效使用非静态成员函数 [英] Invalid use of non-static member function using vector.sort()

查看:76
本文介绍了使用vector.sort()无效使用非静态成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用sort()函数根据第一列对二维矢量进行排序,但是不幸的是,通过传递"compareAscending"函数,我收到了无效使用非静态成员函数compareAscending"的错误.

I want to sort a two-dimensional vector based on its first column using the sort() function but unfortunately, I get an "invalid use of non-static member function compareAscending" error by passing "compareAscending" function.

我也尝试过使函数静态化,但是遇到了同样的问题.

I have also tried to make the function static but got the same problem.

static bool compareAscending(const std::vector<int>& v1, const std::vector<int>& v2) 
{ 
    return (v1[0] < v2[0]); 
} 

这是我想用于排序功能的比较器

This is comparator which I wanna use for the sort function

bool compareAscending(const std::vector<int>& v1, const std::vector<int>& v2) 
{ 
    return (v1[0] < v2[0]); 
} 

这是我想调用的排序功能

And this is the sort function which I wanna call

sort(vect.begin(), vect.end(), compareAscending);

推荐答案

无效使用非静态成员函数compareAscending

invalid use of non-static member function compareAscending

使排序函数成为非类成员,或使其成为 static -或使用lambda:

Make the sorting function a non class member or make it static - or use a lambda:

std::sort(vect.begin(), vect.end(),
    [](const std::vector<int>& v1, const std::vector<int>& v2) {
        return v1[0] < v2[0];
    }
);

一个 static 版本:

class foo {
public:
    static bool compareAscending(const std::vector<int>& v1,
                                 const std::vector<int>& v2) {
        return v1[0] < v2[0];
    }
};

std::sort(vect.begin(), vect.end(), foo::compareAscending);

免费版本:

bool compareAscending(const std::vector<int>& v1,
                      const std::vector<int>& v2) {
    return v1[0] < v2[0];
}

std::sort(vect.begin(), vect.end(), compareAscending);

这篇关于使用vector.sort()无效使用非静态成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆