稳定排序--stable_sort

 

 stable_sort和sort区别:

如果你写一个比较函数:
bool less_len(const string &str1, const string &str2)
{
        return str1.length() < str2.length();
}
此时,"apples" 和 "winter" 就是相等的,如果在"apples" 出现在"winter"前面,用带stable的函数排序后,他们的次序一定不变,如果你使用的是不带"stable"的函数排序,那么排序完 后,"winter"有可能在"apples"的前面。

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    string str;
    while(getline(cin,str))
    {
        string cs;
        for(auto c:str)
        {
            if(isalpha(c))//判断一个字符是否为字母
                cs+=c;
        }
        stable_sort(cs.begin(),cs.end(),[](char a,char b){
            return tolower(a)<tolower(b);//转换成小写
        });
        for(int i=0,j=0;i<str.size();i++)
            if(isalpha(str[i]))cout<<cs[j++];
            else cout<<str[i];
        cout<<endl;
    }
    return 0;
}

 

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值