这篇文章主要介绍了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 style="margin-top: 0px; margin-bottom: 0px; color: rgb(0, 128, 0);">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++ 求数组最大最小值函数的实现
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- C++ 数据结构超详细讲解顺序表 2023-03-25
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- Easyx实现扫雷游戏 2023-02-06
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- ubuntu下C/C++获取剩余内存 2023-09-18
- Qt计时器使用方法详解 2023-05-30
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- C语言详解float类型在内存中的存储方式 2023-03-27
- C语言qsort()函数的使用方法详解 2023-04-26
