如何在 C++ 中使用 STL 找出向量的最大元素?


在本教程中,我们将讨论一个程序,以了解如何在 C++ 中使用 STL 查找向量的最大元素。

要查找给定向量的最大元素,我们将使用 STL 库中的 *max_element() 方法。

示例

 现场演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   //defining the vector
   vector<int> a = { 1, 45, 54, 71, 76, 12 };
   cout << "Vector: ";
   for (int i = 0; i < a.size(); i++)
      cout << a[i] << " ";
   cout << endl;
   //finding the maximum element
   cout << "Max Element = " << *max_element(a.begin(), a.end());
   return 0;
}

输出

Vector: 1 45 54 71 76 12
Max Element = 76

更新于:2020 年 2 月 25 日

6K+ 浏览次数

启动你的 职业生涯

通过完成课程来获得认证

开始
广告
© . All rights reserved.