UVa400 Unix ls命令

题目:VJ:UVa400

代码实现:

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>

using namespace std;

int main()
{
	int N;
	while(scanf("%d",&N) == 1){
		vector<string> strvec;	//文件名数组 
		string fn;
		int maxsize;	//输入文件名最大长度
		//输入 
		for(int i = 0; i < N; ++i){
			cin >> fn;
			if(i == 0)
				maxsize = fn.size();
			if(maxsize < fn.size())
				maxsize = fn.size();
			strvec.push_back(fn);
		}
		sort(strvec.begin(),strvec.end());
		//计算行列数
		int fsize = strvec.size();	//文件名数量 
		int col = (60-maxsize)/(maxsize+2)+1; 
		int row = (fsize - 1)/col + 1;
		/*
		int row = fsize/col;
		if(fsize%col != 0)
			++row;
		*/
		//输出 
		cout << string(60,'-') << endl;
		for(int i = 0; i < row; ++i){
			for(int j = 0; j < col; ++j){
				int n = j * row + i;
				if(n < fsize){
					string ts = strvec[n];
					ts += string(maxsize-ts.size(),' ');
					if(j != col-1)
						ts += string(2,' ');
					cout << ts;
				} 
			}
			cout << endl;
		}
	}
	return 0;
}

总结:

1.刚开始写的时候使用set来存放文件名,顺便就排序了,但要进行输出时,发现要求是按列排序的,没想到怎样格式化输出字符串,参考书中的代码,醒悟可以逆向来做,按表输出,把表中的位置定位到文件名数组中。

2.书中求row行数时也用了一个美好结论,学习了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值