文件名升序排列,优先按照文件名称排序,若文件名相同,则按照后缀排序
Demo code
#ifndef FILENAMESORT_H_
#define FILENAMESORT_H_
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
using namespace std;
const int MAXFILENUM = 100;
// 定义一个结构体来表示文件, a 代表文件名, b 代表文件类型(要么 "File" 要么 "Dir" )
typedef struct node{
string a;//filename
string b;//file type
}Node;
//ASCII 码中,所有大写字母排在所有小写字母前面, 'A'<'Z'<'a'<'z'
// 而这题要求忽略大小写,所以不能直接用字符串的比较。自定义了一个 lt 函数,就是 less than 的意思
// 先把两个字符串全部转化为小写,再比较大小(字典序)
bool lt(string x,string y)
{
int i;
for(i=0;i<x.length();i++)
if(x[i]>='A'&&x[i]<='Z')
x[i]='a'+(x[i]-'A');
for(i=0;i<y.length();i++)
if(y[i]>='A'&&y[i]<='Z')
y[i]='a'+(y[i]-'A');
return x<y;
}
// 自定义的比较函数,先按 b 值升序排列(也就是 "Dir" 排在 "File" 前面)
// 如果 b 值相同,再按 a 升序排列,用的是刚才定义的 lt 函数
bool comp(Node x,Node y)
{
if(x.b!=y.b)
return x.b<y.b;
return lt(x.a,y.a);
}
bool cmp(Node x,Node y)
{//优先按照a排序 若a相同,则按照b排序
if(x.a != x.b)
return x.a < y.a;
else
return x.b < y.b;
}
void test_filename_sort()
{
Node arr[MAXFILENUM];
int size = 0;
string buf;
int last_dot_index;
//3 28.txt 6.txt.txt
while(getline(cin,buf) && strcmp(buf.c_str(),"quit") != 0 )
{
//sscanf(buf,"%s.%s",&arr[size].a,&arr[size].b);
last_dot_index = buf.find_last_of('.');
arr[size].a = buf.substr(0,last_dot_index);//[a,b)
arr[size].b = buf.substr(last_dot_index + 1);
size ++ ;
}
//sort(arr,arr+size,comp);//
sort(arr,arr+size,cmp);//
cout << endl << "---after sort---" << endl;
for(int i=0;i<size;i++)
cout<<arr[i].a<<"."<<arr[i].b<<endl;
}
#endif
Result: