编写一个程序,使堆栈储存100个学生记录
时间: 2024-03-03 08:50:08 浏览: 22
好的,我可以为您提供一个示例程序,使用C++语言实现一个可以储存100个学生记录的堆栈。
```cpp
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int age;
string major;
};
const int MAX_SIZE = 100;
class Stack {
private:
Student stack_array[MAX_SIZE];
int top;
public:
Stack() {
top = -1;
}
bool isEmpty() {
return top == -1;
}
bool isFull() {
return top == MAX_SIZE - 1;
}
void push(Student student) {
if (isFull()) {
cout << "Stack overflow!" << endl;
return;
}
top++;
stack_array[top] = student;
}
void pop() {
if (isEmpty()) {
cout << "Stack underflow!" << endl;
return;
}
top--;
}
Student peek() {
if (isEmpty()) {
cout << "Stack is empty!" << endl;
return {"", 0, ""};
}
return stack_array[top];
}
};
int main() {
Stack student_stack;
// push 100 student records into the stack
for (int i = 1; i <= 100; i++) {
Student student;
student.name = "Student " + to_string(i);
student.age = 18 + i % 5;
student.major = "Major " + to_string(i % 10);
student_stack.push(student);
}
// pop and print all the student records from the stack
while (!student_stack.isEmpty()) {
Student student = student_stack.peek();
cout << student.name << ", " << student.age << ", " << student.major << endl;
student_stack.pop();
}
return 0;
}
```
这个程序使用了一个结构体`Student`来储存每个学生的记录,其中包括姓名、年龄和专业。堆栈的容量被设为100,使用一个类`Stack`来实现堆栈的基本操作,包括`push`、`pop`、`peek`等。在`main`函数中,我们向堆栈中压入100个学生记录,然后依次弹出并打印每个学生的记录。
希望这个示例程序能够帮到您,如有疑问请随时向我提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)