查找栈中的最大元素

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本教程中,你将学习如何在 C++ 编程语言中查找栈(stack)中的最大元素。我们将为你提供一个逐步的指南,教你如何使用栈来查找最大元素,并详细解释每一行代码。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp(("C++")) -.-> cpp/ControlFlowGroup(["Control Flow"]) cpp(("C++")) -.-> cpp/FunctionsGroup(["Functions"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/StandardLibraryGroup(["Standard Library"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/BasicsGroup -.-> cpp/strings("Strings") cpp/ControlFlowGroup -.-> cpp/while_loop("While Loop") cpp/FunctionsGroup -.-> cpp/function_parameters("Function Parameters") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/StandardLibraryGroup -.-> cpp/standard_containers("Standard Containers") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/strings -.-> lab-96137{{"查找栈中的最大元素"}} cpp/while_loop -.-> lab-96137{{"查找栈中的最大元素"}} cpp/function_parameters -.-> lab-96137{{"查找栈中的最大元素"}} cpp/output -.-> lab-96137{{"查找栈中的最大元素"}} cpp/standard_containers -.-> lab-96137{{"查找栈中的最大元素"}} cpp/code_formatting -.-> lab-96137{{"查找栈中的最大元素"}} end

创建一个新的 C++ 文件

~/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() 函数

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++ 编程语言中查找栈中的最大元素。希望本教程对你有所帮助!