如何在C++中使用STL查找向量的最小和最大元素()

给定一个向量, 请在C ++中使用STL查找该向量的最小和最大元素。
例子:

Input: {1, 45, 54, 71, 76, 12}Output: min = 1, max = 76Input: {10, 7, 5, 4, 6, 12}Output: min = 1, max = 76

推荐:请尝试以下方法{IDE}首先, 在继续解决方案之前。方法:
  • 最小或最小元素可以通过以下方式找到* min_element()STL中提供的功能。
  • 最大或最大元素可以在以下帮助下找到* max_element()STL中提供的功能。
语法如下:
*min_element (first_index, last_index); *max_element (first_index, last_index);

下面是上述方法的实现:
// C++ program to find the min and max element // of Vector using *min_element() in STL#include < bits/stdc++.h> using namespace std; int main() { // Get the vector vector< int > a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout < < "Vector: " ; for ( int i = 0; i < a.size(); i++) cout < < a[i] < < " " ; cout < < endl; // Find the min element cout < < "\nMin Element = " < < *min_element(a.begin(), a.end()); // Find the max element cout < < "\nMax Element = " < < *max_element(a.begin(), a.end()); return 0; }

输出如下:
Vector: 1 45 54 71 76 12 Min Element = 1Max Element = 76

【如何在C++中使用STL查找向量的最小和最大元素()】被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C ++ STL通过激烈的问题解决过程来训练和掌握这些概念。

    推荐阅读