本篇內容主要講解“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++標準庫中頭文件<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++怎么求數組的最大和最小值”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。