如何利用C ++中的STL找到向量的最小和最大元素

如何利用C ++中的STL找到向量的最小和最大元素

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

Input: {1, 45, 54, 71, 76, 12}
Output: min = 1, max = 76

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

方法:

  • 可以使用STL提供的 *min_element() 函数来查找最小元素。
  • 可以使用STL提供的 *max_element() 函数来查找最大元素。

语法:

*min_element (first_index, last_index);

*max_element (first_index, last_index);
C++

以下是上述方法的实现:

// 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;
}  
C++

输出:

Vector: 1 45 54 71 76 12 

Min Element = 1
Max Element = 76
C++

时间复杂度: O(N)

辅助空间: O(1)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册