欢迎光临
我们一直在努力

c++怎么求数组的最大和最小值

本篇内容主要讲解“c++怎么求数组的最大和最小值”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“c++怎么求数组的最大和最小值”吧!

求数组元素最大最小值函数

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[5]={1,2,3,0,-20};
cout<<*max_element(a,a+5)<<endl;
cout<<*max_element(a,a+5)<<endl;
return 0;
}

也可以通过这种方式,修改最大值或最小值

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[5]={1,2,3,0,-2},m=10;
*min_element(a,a+5) += *max_element(a,a+5);//把最小元素和最大元素的和 赋给当前最小元素
cout<<*max_element(a,a+5);
return 0;
}

c++中min和max函数

包含在c++标准库中头文件<algorithm>中,在头文件<windows.h>中定义了min,max的宏,若在包含<algorithm>的同时包含<windows.h>会导致函数无法使用。

<windows.h>提供了_cpp_min等函数来代替min函数的功能。

C++11标准:<algorithm>中min函数的原型

default (1) template <class T> const T& min (const T& a, const T& b);
custom (2) template <class T, class Compare>
  const T& min (const T& a, const T& b, Compare comp);
initializer list (3) template <class T> T min (initializer_list<T> il);
template <class T, class Compare>
  T min (initializer_list<T> il, Compare comp);

Return the smallest

Returns the smallest of  a and  b. If both are equivalent,  a is returned.

The versions for  initializer lists (3) return the smallest of all the elements in the list. Returning the first of them if these are more than one.

The function uses  operator< (or  comp, if provided) to compare the values.

eg:custom2<pre >template <class T, class Compare>
  const T& min (const T& a, const T& b, Compare comp);
#include<iostream>
#include<algorithm>
using namespace std;
struct var {
    char *name;
    int key;
    var(char *a,int k):name(a),key(k){}
};
bool comp(const var& l, const var& r) {
    return l.key < r.key;
}
int main() {
    var v1("var1", 2);
    var v2("var2", 3);
    cout << std::min(v1, v2,comp).name << endl;
    return 0;
}

stable_sort,max函数同min

到此,相信大家对“c++怎么求数组的最大和最小值”有了更深的了解,不妨来实际操作一番吧!这里是云搜网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。