使用sort实现C++字符串排序


对于char类型

#include<algorithm>  
#include<cstring>  
#include<cstdio> 

#define M  100000  
#define len 22  
using namespace std;

char str[M][len];
int cmp1(const void *a, const void*b) {
    char *s1 = (char *)a;
    char *s2 = (char *)b;
    return strcmp(s1, s2);
}
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 0;i<n;i++)
        scanf("%s", str[i]);
    qsort(str, n, sizeof(char)*len, cmp1);
    for (int i = 0;i < n;i++)
        printf("%s\n", str[i]);
        return 0;
}

 

对于string类型

#include<algorithm>  
#include<cstring>  
#include<cstdio>  
#include<iostream>  
#define M  100000  
#define len 22  
using namespace std;  
string str[1005];  
int cmp(string a,string b)  
{  
    return a.compare(b)<0;  
}  
int main()  
{  
    int n;  
    scanf("%d", &n);  
    for (int i=0; i<n; i++)  
        cin>>str[i];  
    sort(str, str+n, cmp);  
    return 0;  
}  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM