用动态数组来保存学生的信息c++,不使用类编写,有信息添加函数,在主函数里添加信息
时间: 2024-02-20 18:58:49 浏览: 22
好的,以下是使用动态数组来保存学生信息的 C++ 代码示例,不使用类:
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 定义学生结构体
struct Student {
string name;
int age;
};
// 添加学生信息函数
void addStudent(vector<Student>& students, string name, int age) {
Student student;
student.name = name;
student.age = age;
students.push_back(student);
}
int main() {
// 创建学生信息动态数组
vector<Student> students;
// 添加学生信息到数组中
addStudent(students, "Tom", 18);
addStudent(students, "Jerry", 19);
addStudent(students, "Alice", 20);
// 遍历输出学生信息
for (Student student : students) {
cout << "姓名:" << student.name << ",年龄:" << student.age << endl;
}
return 0;
}
```
在上面的代码中,我们首先使用 `vector` 类型来创建一个动态数组来保存学生信息。然后,我们定义了一个 `addStudent` 函数来向该数组中添加学生信息。最后,我们在主函数中调用 `addStudent` 函数来添加学生信息,并使用 `for` 循环遍历该数组并输出每个学生的姓名和年龄。