📜  C++中的std :: min_element

📅  最后修改于: 2021-05-30 12:17:12             🧑  作者: Mango

为了计算最小的在给定列表中的所有元素,我们的std ::分钟,但是如果我们想找到在整个名单中最小的,而是在列表中的一个子部分。为了达到这个目的,我们在C++中提供了std :: min_element。

std :: min_element是在头文件中定义的,它返回一个迭代器,该迭代器指向在[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.
    
    Return Value: 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 
    #include 
    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.
    
    Return Value: 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 
    #include 
    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 :: max_element
  • std :: max
  • std :: min
  • std ::等于
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”