stl sort demo

文件名升序排列,优先按照文件名称排序,若文件名相同,则按照后缀排序

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:




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值