介绍
在本教程中,你将学习如何在 C++ 编程语言中查找栈(stack)中的最大元素。我们将为你提供一个逐步的指南,教你如何使用栈来查找最大元素,并详细解释每一行代码。
在本教程中,你将学习如何在 C++ 编程语言中查找栈(stack)中的最大元素。我们将为你提供一个逐步的指南,教你如何使用栈来查找最大元素,并详细解释每一行代码。
在 ~/project 目录下创建一个名为 main.cpp 的新文件。在 main.cpp 文件中,包含必要的 C++ 库:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
定义两个函数:findMax() 用于查找栈中的最大元素,show() 用于打印栈中的元素。
void findMax(stack<int> s) {
int m = s.top();
int a;
while (!s.empty()) {
a = s.top();
if (m < a)
m = a;
s.pop();
}
cout << "\n\nThe maximum element of the stack is: " << m << endl;
}
void show(stack<int> s) {
while (!s.empty()) {
cout << " " << s.top();
s.pop();
}
cout << endl;
}
在 main() 函数中,创建一个类型为 int 的新栈,并使用 push() 方法填充元素。
调用 show() 函数以 LIFO(后进先出)顺序打印栈中的元素。
最后,调用 findMax() 函数查找栈中的最大元素。
int main() {
cout << "\n\nWelcome to the Stack Program in C++!\n\n\n";
stack<int> s;
s.push(4);
s.push(2);
s.push(20);
s.push(12);
s.push(52);
s.push(14);
cout << "The elements of the Stack in LIFO order are: ";
show(s);
findMax(s);
return 0;
}
在终端中使用以下命令编译程序:
g++ main.cpp -o main && ./main
程序的输出应如下所示:
Welcome to the Stack Program in C++!
The elements of the Stack in LIFO order are: 14 52 12 20 2 4
The maximum element of the stack is: 52
在本教程中,我们学习了如何在 C++ 编程语言中查找栈中的最大元素。希望本教程对你有所帮助!