当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ max_element用法及代码示例


我们有std::max查找最多 2 个或更多元素,但是如果我们想查找数组、向量、列表或 sub-section 中的最大元素怎么办?为了达到这个目的,我们在 C++ 中使用了 std::max_element。std::max_element是在头文件中定义的,它返回一个迭代器,该迭代器指向[first,last)范围内具有最大值的元素。 std::max_element 可以通过两种方式使用。可以使用以下方法进行比较运算符 <(第一个版本),或使用预定义函数(第二版)。如果多个元素满足最大条件,则迭代器返回指向第一个元素的指针。

这两个版本的定义如下:

  1. 使用“<”比较元素:

句法:

    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.

    返回值:     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.

CPP


// 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

时间复杂度:在)

辅助空间:O(1)

2。基于预定义函数的比较:

用法:

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.

返回值: 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.

CPP


// 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

时间复杂度:在)

辅助空间:O(1)

相关文章:



相关用法


注:本文由纯净天空筛选整理自佚名大神的英文原创作品 max_element in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。