C++中的max_element用法详解

2021年3月10日15:53:07 发表评论 3,123 次浏览

我们有

std :: max

最多可以找到2个或更多元素, 但是如果我们想在数组, 向量, 列表或子节中找到最大的元素, 该怎么办。为了达到这个目的, 我们在C ++中有std :: max_element

std :: max_element

在头文件中定义

然后返回一个迭代器, 该迭代器指向在[first, last)范围内具有最大值的元素。

std :: max_element可以以两种方式使用。可以使用以下两种方法进行比较运算符<(第一个版本), 或使用预定义功能(第二版)。如果一个以上元素满足最大条件, 则迭代器返回指向此类元素中第一个的点。

这两个版本定义如下:

使用" <"比较元素:

语法如下:

template 
     
      
ForwardIterator max_element (ForwardIterator first, ForwardIterator last);
     

first: Forward iterator pointing to the beginning of the range.
last: Forward iterator pointing to the end of the range.

Return Value: It returns a pointer to the largest 
element in the range, and in case if there are more than 
one such element, then it points to the first one.

It points to the last in case the range is empty.
// C++ program to demonstrate the use of std::max_element
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
     int v[] = { 'a' , 'c' , 'k' , 'd' , 'e' , 'f' , 'h' };
  
     // Finding the maximum value between the first and the
     // fourth element
  
     int * i1;
     i1 = std::max_element(v, v + 4);
  
     cout << char (*i1) << "\n" ;
     return 0;
}

输出如下:

k

对于基于预定义功能的比较:

语法如下:

template 
     
      
ForwardIterator max_element (ForwardIterator first, ForwardIterator last, Compare comp);
     
Here, first and last are the same as previous case.
comp: Binary function that accepts two elements 
in the range as arguments, and returns a value convertible to bool.

The value returned indicates whether the element passed as first argument 
is considered less than the second.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.

Return Value: It returns a pointer to the largest element 
in the range, and in case if there are more than one such element, then it points to the first one.
It points to the last in case the range is empty.
// C++ program to demonstrate the use of std::max_element
#include <iostream>
#include <algorithm>
using namespace std;
  
// Defining the BinaryFunction
bool comp( int a, int b)
{
     return (a < b);
}
  
int main()
{
     int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 };
  
     // Finding the maximum value between the third and the
     // ninth element
  
     int * i1;
     i1 = std::max_element(v + 2, v + 9, comp);
  
     cout << *i1 << "\n" ;
     return 0;
}

输出如下:

12

相关文章:

  • std :: max
  • std :: min
  • std ::等于
  • C ++中的std :: min_element

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C ++ STL通过激烈的问题解决过程来训练和掌握这些概念。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: