スタックの最大要素を見つける

C++Beginner
オンラインで実践に進む

はじめに

このチュートリアルでは、C++ プログラミング言語でスタックの最大要素を見つける方法を学びます。スタックを使って最大要素を見つける方法について段階的なガイドを提供し、各行のコードを詳細に説明します。

新しい C++ ファイルを作成する

~/project ディレクトリに main.cpp という名前の新しいファイルを作成します。main.cpp ファイルには、必要な C++ ライブラリを含めます。

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

スタック用の関数を定義する

スタックの最大要素を見つけるための findMax() 関数と、スタックの要素を表示するための show() 関数の 2 つを定義します。

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++ プログラミング言語でスタック内の最大要素を見つける方法を学びました。このチュートリアルがあなたに役立てば幸いです!