【c++】 sort函数的使用(printf格式)

首先注意下如果运行程序时提示 exe 文件无法写入,那么可能是修改程序前的黑框命令栏还存在,只需要关闭命令行即可。

这里主要是实验下printf 即 c 语言格式的输出:

#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<vector>
using namespace std;

int main()
{
	vector<int> v(100);
	int n;
	printf("请输入要排序的数字的个数: ");
	while (scanf("%d", &n) != EOF)
	{
		printf("请输入%d个数: ",n);
		for (int i = 0; i < n; i++)
		{
			scanf("%d",&v[i]);
		}
		sort(v.begin(),v.begin() + n);
		for (int i = 0; i < n; i++)
			printf("%d ",v[i]);
		printf("\n请再次输入要排序的数字的个数: ");
	}
	return 0;
}

运行结果:

请输入要排序的数字的个数: 4
请输入4个数: 3 2 1 4
1 2 3 4
请再次输入要排序的数字的个数: 3
请输入3个数: 3 2 1
1 2 3
请再次输入要排序的数字的个数:

注意vector 要事先分配一个较大的空间,以及 sort(v.begin(),v.begin() + n) 的写法。

数组的写法:

#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<vector>
using namespace std;

int main()
{
	int a[100];
	int n;
	printf("请输入要排序的数字的个数: ");
	while (scanf("%d", &n) != EOF)
	{
		printf("请输入%d个数: ",n);
		for (int i = 0; i < n; i++)
		{
			scanf("%d",&a[i]);
		}
		sort(a,a + n);
		for (int i = 0; i < n; i++)
			printf("%d ",a[i]);
		printf("\n请再次输入要排序的数字的个数: ");
	}
	return 0;
}

运行结果:

请输入要排序的数字的个数: 4
请输入4个数: 3 1 24 3
1 3 3 24
请再次输入要排序的数字的个数: 3
请输入3个数: 1 3 2
1 2 3
请再次输入要排序的数字的个数:
^Z^Z^Z^Z^Z^Z
^Z^Z
^Z
请按任意键继续. . .

降序第三个参数:

#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<vector>
using namespace std;

bool cmp(int x, int y)
{
	return x > y;
}
int main()
{
	int a[100];
	int n;
	printf("请输入要排序的数字的个数: ");
	while (scanf("%d", &n) != EOF)
	{
		printf("请输入%d个数: ",n);
		for (int i = 0; i < n; i++)
		{
			scanf("%d",&a[i]);
		}
		sort(a,a + n,cmp);
		for (int i = 0; i < n; i++)
			printf("%d ",a[i]);
		printf("\n请再次输入要排序的数字的个数: ");
	}
	return 0;
}

运行结果:

请输入要排序的数字的个数: 4
请输入4个数: 1 22 3 4
22 4 3 1
请再次输入要排序的数字的个数: 3
请输入3个数: 1 2 3
3 2 1
请再次输入要排序的数字的个数: ^C请按任意键继续. . .

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值