比较容器内字符串大小并按照从小到大顺序排序及输出

本例实际应用场景是包含以时间命名的文件,通过比较时间先后将容器内字符串进行排序,此处比较函数仅使用了compare,(实际有具体的遍历文件夹下所有文件到容器内(这里手动塞了几个时间数据,因此直接使用compare比较大小即可),并找到命名中时间部分,然后比较进行排序)

#include <iostream>
#include <vector>
#include <algorithm> 
using namespace std;

bool myfunction(string t1,string t2){
//printf("%d\n",t1.compare(t2));
if(t1.compare(t2)>0)
	return 0;
else
	return 1;
}

int main()
{
vector<string> str;
str.push_back("202304201826");
str.push_back("202304201326");
str.push_back("202304201328");
str.push_back("202304211328");
str.push_back("202304101328");
str.push_back("202303201328");
str.push_back("202304201826");
str.push_back("202304201326");
str.push_back("202304201328");
str.push_back("202304211328");
str.push_back("202304101328");
str.push_back("202303201328");
str.push_back("202304201826");
str.push_back("202304201326");
str.push_back("202304201328");
str.push_back("202304211328");
str.push_back("202304101328");
str.push_back("202303201328");
str.push_back("202304201826");
str.push_back("202304201326");
str.push_back("202304201328");
str.push_back("202304211328");
str.push_back("202304101328");
str.push_back("202303201328");
printf("size:%lu \n",str.size());
for(int i=0;i<str.size();i++)
	cout<<str[i]<<endl;
sort(str.begin(),str.end(),myfunction);
for(int j=0;j<str.size();j++)
	cout<<str[j]<<endl;
//cout<<str[0].compare(str[1])<<endl;
//cout<<str[1].compare(str[2])<<endl;
//cout<<str[0].compare(str[2])<<endl;

printf("size:%lu \n",str.size());
	for(int i=0;i<str.size();)
	{
		str.erase(str.begin());
	}

printf("size:%lu \n",str.size());
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值