用C++代码定义一个包含学生信息(学号,姓名,成绩)的顺序表,使其具有如下功能
时间: 2023-09-11 13:05:00 浏览: 96
1. 初始化顺序表
2. 插入学生信息
3. 删除学生信息
4. 修改学生信息
5. 查找学生信息
6. 输出所有学生信息
7. 统计学生总数
8. 清空顺序表
以下是对应的C代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct Student {
int id;
char name[20];
float score;
} Student;
typedef struct SeqList {
Student data[MAX_SIZE];
int length;
} SeqList;
void init_list(SeqList *list) {
list->length = 0;
}
int insert(SeqList *list, int pos, Student stu) {
if (pos < 1 || pos > list->length + 1) {
printf("Error: Invalid position\n");
return 0;
}
if (list->length >= MAX_SIZE) {
printf("Error: List is full\n");
return 0;
}
for (int i = list->length; i >= pos; i--) {
list->data[i] = list->data[i - 1];
}
list->data[pos - 1] = stu;
list->length++;
return 1;
}
int delete(SeqList *list, int pos) {
if (pos < 1 || pos > list->length) {
printf("Error: Invalid position\n");
return 0;
}
for (int i = pos - 1; i < list->length - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->length--;
return 1;
}
int modify(SeqList *list, int pos, Student stu) {
if (pos < 1 || pos > list->length) {
printf("Error: Invalid position\n");
return 0;
}
list->data[pos - 1] = stu;
return 1;
}
int search(SeqList *list, int id) {
for (int i = 0; i < list->length; i++) {
if (list->data[i].id == id) {
return i + 1;
}
}
return 0;
}
void print_all(SeqList *list) {
printf("ID\tName\tScore\n");
for (int i = 0; i < list->length; i++) {
printf("%d\t%s\t%.2f\n", list->data[i].id, list->data[i].name, list->data[i].score);
}
}
int count(SeqList *list) {
return list->length;
}
void clear(SeqList *list) {
list->length = 0;
}
int main() {
SeqList list;
init_list(&list);
Student s1 = {1001, "Tom", 90};
Student s2 = {1002, "Jerry", 85};
Student s3 = {1003, "Mary", 95};
insert(&list, 1, s1);
insert(&list, 2, s2);
insert(&list, 3, s3);
print_all(&list);
printf("Count: %d\n", count(&list));
modify(&list, 2, (Student){1002, "John", 88});
print_all(&list);
printf("Search result: %d\n", search(&list, 1002));
delete(&list, 1);
print_all(&list);
clear(&list);
printf("Count: %d\n", count(&list));
return 0;
}
```
输出结果:
```
ID Name Score
1001 Tom 90.00
1002 Jerry 85.00
1003 Mary 95.00
Count: 3
ID Name Score
1001 Tom 90.00
1002 John 88.00
1003 Mary 95.00
Search result: 2
ID Name Score
1002 John 88.00
1003 Mary 95.00
Count: 0
```
阅读全文