结构体的小练习

1.输入输出学生数据

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define N 2

struct student
{
	char num[2];
	char name[8];
	int score[4];
}STU[N] = {0};

input(stu)
{
	struct student STU[N];     //声明结构体变量STU[N]
	int i = 0, j = 0;
	for (i = 0; i < N; i++)
	{
		printf("\n please input %d of %d", i + 1, N);
		printf("num:");
		scanf("%s", STU[i].num);
		printf("name:");
		scanf("%s", STU[i].name);
		for (j = 0; j < 3; j++)
		{
			printf("score %d.", j + 1);
			scanf("%d", &STU[i].score[j]);
		}
		printf("\n");
	}
}

output()
{
	struct student STU[N];
	int i = 0, j = 0;
	printf("\nNO.name.SCO1.SCO2.SCO3\n");
	for (i = 0; i < N; i++)
	{
		printf("%-6s%-10s", STU[i].num, STU[i].name);
		for (j = 0; j < 3; j++)
		{
			printf("%-8d", STU[i].score[j]);
			printf("\n");
		}
	}
}

int main()
{
	input();
	output();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中,结构体排序练习通常涉及到如何使用标准库中的算法对包含自定义数据类型的结构体数组或容器进行排序。这里我们可以举一个简单的例子,假设有一个名为`Student`的结构体,包含`name`和`age`两个成员: ```cpp struct Student { std::string name; int age; }; ``` 你可以用以下几种方法对`Student`结构体数组进行排序: 1. **直接排序:**如果年龄是排序的主要依据,你可以定义一个比较函数(`compare`),然后使用`std::sort`函数: ```cpp bool compareStudents(const Student& s1, const Student& s2) { return s1.age < s2.age; } int main() { Student students[] = {{"Alice", 20}, {"Bob", 18}, {"Charlie", 22}}; std::sort(students, students + sizeof(students) / sizeof(students), compareStudents); // 现在students数组按年龄升序排列 } ``` 2. **使用STL算法:**如果你的结构体已经实现了`<`运算符,那么可以直接使用`std::stable_sort`: ```cpp bool studentLess(const Student& s1, const Student& s2) { return s1.age < s2.age; } int main() { std::vector<Student> students = {{"Alice", 20}, {"Bob", 18}, {"Charlie", 22}}; std::stable_sort(students.begin(), students.end(), studentLess); } ``` 3. **自定义比较器(C++11及以上):**也可以使用lambda表达式来创建一个可传递的比较器: ```cpp int main() { std::vector<Student> students = {{"Alice", 20}, {"Bob", 18}, {"Charlie", 22}}; std::sort(students.begin(), students.end(), [](const Student& s1, const Student& s2) { return s1.age < s2.age; }); } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值