C++中sort的比较函数写法

原文链接:https://blog.csdn.net/maverick1990/article/details/37738601

定义排序函数:

方法1:声明外部比较函数

bool Less(const Student& s1, const Student& s2)
{
return s1.name < s2.name; //从小到大排序
}
std::sort(sutVector.begin(), stuVector.end(), Less);
注意:比较函数必须写在类外部(全局区域)或声明为静态函数

当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样。
否则,会出现<unresolved overloaded function type>错误

方法2:重载类的比较运算符
bool operator<(const Student& s1, const Student& s2)
{
return s1.name < s2.name; //从小到大排序
}
std::sort(sutVector.begin(), stuVector.end());

方法3:声明比较类
struct Less
{
bool operator()(const Student& s1, const Student& s2)
{
return s1.name < s2.name; //从小到大排序
}
};

std::sort(sutVector.begin(), stuVector.end(), Less());

原文链接: https://www.cnblogs.com/shilipojianshen/p/13304614.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++中sort的比较函数写法

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/200410

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午8:25
下一篇 2023年2月12日 下午8:25

相关推荐