C++基础之结构体数组

结构体数组:将自定义的结构体放入到数组中方便维护。

#include <iostream>
using namespace std;
#include<string>

/*
	定义一个结构体
*/
struct Student
{
	string name;
	int age;
	int score;
};

int main() 
{
	/*
		创建结构体数组并赋值
	*/
	struct Student stuArray[3] = 
	{
		{"小明",19,60},
		{"小红",18,70},
		{"小军",20,100}
	};

	/*
		修改结构体数组中的元素的值
	*/
	stuArray[2].age = 90;

	/*
		遍历结构体数组
	*/
	int length = sizeof(stuArray) / sizeof(stuArray[0]);//数组长度:3

	for (int i = 0; i < length; i++)
	{
		cout << stuArray[i].name << stuArray[i].age << stuArray[i].score << endl;
	}
	
	system("pause");
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个示例代码,演示如何使用C语言对结构体数组进行排序。假设我们有一个结构体定义如下: ```c typedef struct { int id; char name[20]; float score; } Student; ``` 我们可以使用qsort函数对结构体数组进行排序,该函数使用快速排序算法。在调用qsort函数时,我们需要提供以下参数: - 基础数组的起始地址 - 数组中元素的数量 - 每个元素的大小 - 一个指向比较函数的指针 比较函数用于比较两个元素的大小,如果第一个元素应该排在第二个元素之前,则返回负数;如果第一个元素应该排在第二个元素之后,则返回正数;如果两个元素相等,则返回0。 以下是一个使用qsort函数对结构体数组进行按分数从高到低排序的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int id; char name[20]; float score; } Student; int compare(const void* a, const void* b) { const Student* s1 = (const Student*)a; const Student* s2 = (const Student*)b; if (s1->score < s2->score) { return 1; } else if (s1->score > s2->score) { return -1; } else { return 0; } } int main() { Student students[] = { {1, "Alice", 85}, {2, "Bob", 92}, {3, "Charlie", 76}, {4, "David", 89}, {5, "Eva", 94}, }; int num_students = sizeof(students) / sizeof(Student); qsort(students, num_students, sizeof(Student), compare); for (int i = 0; i < num_students; i++) { printf("%d\t%s\t%.1f\n", students[i].id, students[i].name, students[i].score); } return 0; } ``` 在此示例代码中,我们首先定义了一个包含5个学生的结构体数组。我们计算数组中元素的数量,并将其传递给qsort函数。然后,我们传递每个元素的大小和compare函数的指针。 compare函数根据学生的分数比较两个学生的大小。我们首先将void指针强制转换为指向Student结构体的指针,然后使用指针访问结构体的score字段。如果第一个学生的分数小于第二个学生的分数,则返回1,表示第一个学生应该排在第二个学生之后。如果第一个学生的分数大于第二个学生的分数,则返回-1,表示第一个学生应该排在第二个学生之前。如果两个学生的分数相等,则返回0。 最后,我们使用for循环遍历已排序的数组,并使用printf函数打印每个学生的信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值