蓝桥杯题目——对字符串排序

本文介绍了如何使用C++实现对字符串数组按字典序排序,并区分了长度排序与普通排序。首先展示了如何对字符串直接按字典序升序进行排序,然后讲解了如何对相同长度的字符串进行后续排序。接着,另一段代码则演示了如何先按字符串长度排序,再根据长度内的字典序进行排列。

对字符串字典序排序

#include <bits/stdc++.h>
using namespace std;

char ch[1001][5];

struct stu
{
	string str;
}stu[1005];

bool cmp(struct stu a,struct stu b)
{
	return a.str < b.str;
}

int main()
{
	for(int i = 0;i < 1000;i ++)
	{
		stu[i].str = to_string(i+1);
	}
	sort(stu,stu+1000,cmp);
	for(int i = 0;i < 1000;i ++)
	{
		cout << stu[i].str << endl;
	}
	
	return 0;
}

对字符串先长度排序,之后同长度内排序

#include <bits/stdc++.h>
using namespace std;

char ch[1001][5];
char* pch[1001];

bool cmp(char* a,char* b)
{
	if(strcmp(a,b) < 0) return true;
	return false;
}

int main()
{
	for(int i = 0;i < 1000;i ++)
	{
		sprintf(ch[i],"%d",i + 1);
		pch[i] = ch[i];
	}
	sort(pch,pch+1000,cmp);
	for(int i = 0;i < 1000;i ++)
	{
		cout << ch[i] << endl;
	}
	
	return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值