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


C++ std::min_element用法及代码示例


为了计算给定列表中所有元素中的最小元素,我们有std::min,但是如果我们想在列表的sub-section中而不是整个列表中找到最小元素,该怎么办。为此,我们在C++中提供了std::min_element。

std::min_element在头文件<algorithm>中定义,它返回一个迭代器,该迭代器指向在[first,last)范围内具有最小值的元素。

与可以以三种方式使用的std::min不同,std::min_element可以以两种方式使用。可以使用运算符<(第一个版本)或使用预定义的函数(第二个版本)来执行比较。如果一个以上的元素满足最小条件,则迭代器将返回指向此类元素中第一个的元素。这两个版本定义如下:


  1. 使用“ <”比较元素:
    用法:
    template 
    ForwardIterator min_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 return a pointer to the smallest 
    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::min_element 
    #include <iostream> 
    #include <algorithm> 
    using namespace std; 
    int main() 
    { 
        int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; 
      
        // Finding the minimum value between the third and the 
        // fifth element 
      
        int* i1; 
        i1 = std::min_element(v + 2, v + 5); 
      
        cout << *i1 << "\n"; 
        return 0; 
    }

    输出:

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

    用法:

    template 
    ForwardIterator min_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 return a pointer to the smallest 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::min_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 minimum value between the third and the 
        // ninth element 
      
        int* i1; 
        i1 = std::min_element(v + 2, v + 9, comp); 
      
        cout << *i1 << "\n"; 
        return 0; 
    }

    输出:

    1
    

相关文章:



相关用法


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