比较日期大小一个好的办法 stringstream

比较日期有时候让人头疼,需要考虑很多情况,这里通过stringstream的方法实现一组日期的排序。

#include <iostream>
using namespace std;
#include<algorithm>
#include<sstream>
#include<iomanip>

struct Date{     //创建日期结构体
	int year, month, day;
};

bool cmp(Date s1,Date s2)
{
	string date1, date2;
	stringstream stream1;
	//把日期输进流里。
	stream1 << s1.year << setfill('0') << setw(2) << s1.month << setfill('0') << setw(2) << s1.day;
	//流的值赋给date1.
	date1 = stream1.str();

	stringstream stream2;
	stream2 << s2.year << setfill('0') << setw(2) << s2.month << setfill('0') << setw(2) << s2.day;
	date2 = stream2.str();
       //返回小的值
	return (date1<date2);

}

int main()
{
	int n;
	cin >> n;
	Date date[100];    //创建结构体数组
	for (int i = 0; i < n; i++)
	{
		cin >> date[i].year >> date[i].month >> date[i].day;
	}

	sort(date,date+n,cmp);    //调用
	
	cout << endl;
	for (int i = 0; i < n; i++)
		cout << date[i].year << " " << date[i].month << " " << date[i].day << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值