字符串排序与sort()函数

字符串排序与sort()函数

程序示例

描述
给定 n 个字符串,请对 n 个字符串按照字典序排列。
数据范围:1≤n≤1000  ,字符串长度满足1≤len≤100 

输入描述:
输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。
输出描述:
数据输出n行,输出结果为按照字典序排列的字符串。
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

bool comp(string a,string b){
    return a<b;//升序排列
}

int main(){
    int n;
    cin>>n;
    string str[n];
    
    for(int i=0;i<n;i++){
        cin>>str[i];
    }

    sort(str,str+n,comp);
    
    for(int j=0;j<n;j++){
        cout<<str[j]<<endl;
    }
}

关于sort()函数

  1. sort()函数位于头文件

    #include

  2. sort()函数的两种常见语法

   //对 [first, last) 区域内的元素做默认的升序排序
   void sort (RandomAccessIterator first, RandomAccessIterator last);
   //按照指定的 comp 排序规则,对 [first, last) 区域内的元素进行排序
    void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
  • 两参数示例

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main() {
        int a[20] = { 21,65,21,51,85,1,24,10 };
        cout << "原数列:";
        for (int i = 0; i < 20; i++) cout << a[i] <<" ";
        cout << endl;
    
        sort(a, a + 20);//a指向数组的首地址;sort的两个参数分别指向排序内容的首尾地址;默认为升序排列
        cout << "排序后:";
        for (int i = 0; i < 20; i++) cout <<a[i] << " ";
    }
    

    输出

    原数列:21 65 21 51 85 1 24 10 0 0 0 0 0 0 0 0 0 0 0 0
    排序后:0 0 0 0 0 0 0 0 0 0 0 0 1 10 21 21 24 51 65 85
    
  • 三参数示例

    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    //以普通函数的方式实现自定义排序规则
    bool myfunction(int i, int j) { return i < j; }//升序排列
    bool myfunction2(int i, int j) { return i > j; }//降序排列
    
    int main() {
        vector<int> a{ 21,65,21,51,85,1,24,10 };
    
        sort(a.begin(), a.begin() + 4,myfunction);//(21 21 51 65) 85 1 24 10
        cout << "myfunction排序后:";
        for (int i = 0; i < 8; i++) cout <<a[i] << " ";
        cout << endl;
    
        sort(a.begin()+4, a.begin() + 8, myfunction2);//21 21 51 65( 85 24 10 1)在第一次排序的基础上后4个数的排序
        cout << "myfunction2排序后:";
        for (int i = 0; i < 8; i++) cout << a[i] << " ";
        cout << endl;
    
        return 0;
    }
    
  • 参考链接

    C++ sort排序函数用法_浅然言而信的博客-CSDN博客_c++ sort排序

    C++ sort()排序函数用法详解 (biancheng.net)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值