當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。