1.使用动态数组来保存学生的信息。按照如下程序模板的基础上进行编写。
时间: 2024-02-06 21:10:20 浏览: 27
下面是一个使用动态数组保存学生信息的示例程序:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student {
public:
string name;
int age;
double score;
Student(string name, int age, double score) {
this->name = name;
this->age = age;
this->score = score;
}
};
int main() {
vector<Student> students;
students.push_back(Student("Tom", 18, 90.5));
students.push_back(Student("Jerry", 19, 85.0));
students.push_back(Student("Alice", 20, 92.0));
for (int i = 0; i < students.size(); i++) {
cout << "Name: " << students[i].name << ", Age: " << students[i].age << ", Score: " << students[i].score << endl;
}
return 0;
}
```
在这个程序中,我们首先定义了一个 `Student` 类来表示学生信息。然后我们使用 `vector` 来保存学生信息(每个学生对应一个 `Student` 对象),并使用 `push_back` 方法将学生信息添加到 `vector` 中。最后,我们使用 `for` 循环遍历 `vector` 中的每个学生信息,并输出其属性值。
运行此程序,将得到以下输出:
```
Name: Tom, Age: 18, Score: 90.5
Name: Jerry, Age: 19, Score: 85
Name: Alice, Age: 20, Score: 92
```
这说明我们成功地使用动态数组保存了学生信息,并且能够遍历输出每个学生的属性值。