{"title":"C++顺序表插入学生信息:实例教程与代码解析","description":"本教程详细介绍了如何在C++中使用顺序表存储学生信息,并实现插入操作。通过示例代码和注释,展示了如何定义结构体、创建顺序表、输入插入位置和学生信息、进行插入操作,最后输出所有学生信息。","keywords":"C++, 顺序表, 数组, 结构体, 插入操作, 学生信息, 代码示例, 教程","content":"#include "iostream"\n#include "string"\nusing namespace std;\n\nstruct Student {\n string name;\n int age;\n};\n\nconst int MAX_SIZE = 4; // 最大容量为4\n\nint main() {\n Student students[MAX_SIZE] = {\n {"小括狐", 9},\n {"艾尔", 10},\n {"卡莉娅", 8}\n };\n\n int insertPos;\n cout << "请输入要插入的位置(1-4):";\n cin >> insertPos;\n\n if (insertPos < 1 || insertPos > 4) {\n cout << "输入位置无效!" << endl;\n return 0;\n }\n\n Student newStudent;\n cout << "请输入待插入的学生信息(姓名 年龄):";\n cin >> newStudent.name >> newStudent.age;\n\n // 向顺序表中插入新的学生信息\n for (int i = MAX_SIZE - 1; i > insertPos - 1; i--) {\n students[i] = students[i - 1];\n }\n students[insertPos - 1] = newStudent;\n\n // 输出所有学生信息\n cout << "所有学生信息:" << endl;\n for (int i = 0; i < MAX_SIZE; i++) {\n cout << "姓名:" << students[i].name << " 年龄:" << students[i].age << endl;\n }\n\n return 0;\n}\n\n该程序首先定义了一个Student结构体,用于存储学生的姓名和年龄。然后定义了一个大小为4的顺序表数组students,初始化了3个学生的信息。\n\n接下来,程序要求输入要插入的位置,以及待插入学生的信息。然后使用一个循环将插入位置后的学生信息依次向后移动一位,为新的学生信息腾出位置。最后,遍历顺序表数组,输出所有学生的信息。\n\n运行程序,按照提示输入插入位置和待插入学生信息,即可输出4个学生的信息。"}


原文地址: https://www.cveoy.top/t/topic/pomV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录