logo

C++ の std::max

C++標準::最大 function はヘッダー ファイル内で定義された組み込み関数であり、渡された最大値を見つけるために使用されます。複数ある場合は、最初のものを返します。

次の方法で実装できます。



  1. 引数で渡された 2 つの数値を比較し、2 つの数値のうち大きい方を返します。 両方が等しい場合は、最初のものを返します。
  2. を使用して 2 つの数値を比較することもできます。 二項関数 、ユーザーによって定義され、std::max() の引数として渡されます。
  3. を見つけたい場合にも役立ちます。 最大の要素 指定されたリスト内にあるものを返し、リスト内に複数のものが存在する場合は最初のリストを返します。

1. <: を使用して要素を比較する場合:

構文:

const T& max (const T& a , const T& b );>

パラメーター:

    a: 比較する値 b: 比較する値

戻り値:



  • 2 つの値のうち大きい方を返します。
  • 両方が等しい場合は、最初の値を返します。

注記 : T は、クラス テンプレートで定義された型名です。

例:

C++






シルパ・シェティ

// C++ program to demonstrate> // the use of std::max> #include> #include> using> namespace> std;> // Driver code> int> main()> {> >// Comparing ASCII values of a and b> >cout << std::max(>'a'>,>'b'>) <<>' '>;> >// Returns the first one if both> >// the numbers are same> >cout << std::max(7, 7);> >return> 0;> }>

>

>

出力

b 7>

時間計算量: ○(1)
補助スペース: ○(1)

2. 事前定義関数を使用して要素を比較する場合:

構文:

const T& max (const T& a , const T& b , Compare comp );>

パラメーター:

int Java へのロング
    a: 比較する値 b: 比較する値 comp: T 型の 2 つの値を引数として受け取り、bool に変換可能な値を返すバイナリ関数。返される値は、最初の引数として渡された要素が 2 番目の引数より小さいとみなされるかどうかを示します。

戻り値:

  • 2 つの値のうち大きい方を返します。
  • 両方が等しい場合は、最初の値を返します。

例:

C++




// C++ program to demonstrate> // the use of std::max> #include> #include> using> namespace> std;> // Defining the binary function> bool> comp(>int> a,>int> b)> {> >return> (a } // Driver code int main() { int a = 7; int b = 28; cout << std::max(a,b,comp) << ' '; // Returns the first one if both // the numbers are same cout << std::max(7,7,comp); return 0; }>

>

Java と C++ の比較

>

出力

28 7>

時間計算量: ○(1)
補助スペース: ○(1)

3. リスト内の最大の要素を見つけるには:

構文:

T max (initializer_list il , Compare comp );>

パラメーター:

    il:initializer_list オブジェクト。 comp: オプションでスキップできるコンパレータ関数。

戻り値: リストの最大値が返されます。

以下は、リスト内の最大要素を見つけるための C++ プログラムです。

文字列配列

CPP




// C++ program to demonstrate> // the use of std::max> #include> #include> using> namespace> std;> // Defining the binary function> bool> comp(>int> a,>int> b)> {> >return> (a } // Driver code int main() { // Finding the largest of all the numbers cout << std::max({1, 2, 3, 4, 5, 10, -1, 7},comp) << ' '; return 0; }>

>

>

出力

10>

時間計算量: の上)
補助スペース: ○(1)

関連記事:

  • std::max_element
  • 標準::分
  • std::等しい
  • C++ の std::min_element