【待完善】c++ stl sort的用法

目录

 

1.声明外部比较函数

2.声明比较类

3.重载类的比较运算符

4.Lambda表达式

5.笔试题


1.声明外部比较函数

bool Less(const Student& s1, const Student& s2)
{
    return s1.name < s2.name; //从小到大排序
}
std::sort(sutVector.begin(), stuVector.end(), Less);

s1.name < s2.name //从小到大排序

s1.name > s2.name//从大到小排序

2.声明比较类

struct Less
{
    bool operator()(const Student& s1, const Student& s2)
    {
        return s1.name < s2.name; //从小到大排序
    }
};

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

3.重载类的比较运算符

4.Lambda表达式

std::sort(sutVector.begin(), stuVector.end(), [](const Student& s1, const Student& s2)->bool
{
    return s1.name < s2.name;
});

https://www.cnblogs.com/DswCnblog/p/5629165.html c++11Lambda表达式

https://www.cnblogs.com/jimodetiantang/p/9016826.html c++11之Lambda表达式

https://blog.csdn.net/lixiaogang_theanswer/article/details/80905445 c++11之Lambda函数的详细使用

5.笔试题

   完成Mycomp,使得数组a按字符串长度排序,字符串长度一样时,按字符串大小排序。

int main()
{
    std::vector<std::string> strs;
    std::sort(strs.begin(), strs.end(), MyComp() );
    struct MyComp
    {

    };
}

答案:

struct MyComp
    {
        bool operator()(const std::string &str1, const std::string &str2)
        {
            int len1 = str1.length();
            int len2 = str2.length();
            if(len1!=len2)
            {
                return (len1<len2);
            }
            return (str1.compare(str2)<0);
        }
    };

测试代码:

int main()
{
    std::vector<std::string> strs;
    strs.push_back("hi");
    strs.push_back("hello");
    strs.push_back("world");
    strs.push_back("123");
    strs.push_back("bcde");
    strs.push_back("bbcd");
    std::sort(strs.begin(), strs.end(), MyComp() );
    for (int i = 0; i < 6; i++)
    {
        cout<<strs[i]<<endl;
    }
}

https://www.cnblogs.com/nihow/p/4297102.html  C++<algorithm>中sort的比较函数写法

https://blog.csdn.net/soul_97/article/details/78183429 STL库函数sort的用法详解

https://www.cnblogs.com/moujun1001/p/9629112.html stl之sort函数使用方法

http://www.cplusplus.com/reference/algorithm/sort/ c++ reference std::sort

https://blog.csdn.net/wanghaofeng/article/details/7317442 STL sort使用及重载

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值