C++中的std::min_element解析和用法介绍

2021年3月15日08:57:46 发表评论 910 次浏览

为了计算给定列表中所有元素中的最小元素, 我们有std :: min, 但是如果我们不想在整个列表中找到最小的, 而是在列表的小节。为了达到这个目的, 我们在C ++中有std :: min_element

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

与可以三种方式使用的std :: min不同, std :: min_element可以用于

两种方式

。可以使用运算符<(第一版)或使用预定义功能(第二版)来执行比较。如果有多个元素满足最小条件, 则迭代器返回指向此类元素中第一个的点。

这两个版本定义如下:

使用" <"比较元素:

语法如下:

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

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

语法如下:

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 <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 :: max_element
  • std :: max
  • std :: min
  • std ::等于

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

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

木子山

发表评论

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