網站首頁 編程語言 正文
求數組元素最大最小值函數
#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
原文鏈接:https://blog.csdn.net/qq_36238595/article/details/54755327
相關推薦
- 2023-07-16 uniapp 小程序訂閱消息報錯( wx.requestSubscribeMessage is no
- 2022-12-24 提升Go語言開發效率的小技巧實例(GO語言語法糖)匯總_Golang
- 2022-10-01 React構建簡潔強大可擴展的前端項目架構_React
- 2022-05-28 python非單一.py文件用Pyinstaller打包發布成exe_python
- 2022-02-14 el-form的label和表單自適應填滿一行且靠左對齊
- 2022-02-13 搞明白this指向,走遍天下都不怕(一)
- 2023-01-12 Redis中Bloom?filter布隆過濾器的學習_Redis
- 2022-09-29 ASP.NET?MVC實現多選下拉框保存并顯示_實用技巧
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支