1. min_element() / max_element()函數(shù)簡(jiǎn)單介紹
?用于查找容器或者數(shù)組區(qū)間內(nèi)的最值的時(shí)候進(jìn)行搜索
2. min_element() / max_element()使用分析
? Iterator min_element() / max_element(排序起始位置,排序結(jié)束位置,排序方式)
? A. 可以省略排序方式
? 省略排序方式則默認(rèn)min_element()查找區(qū)間內(nèi)的最小值,max_element()查找區(qū)間內(nèi)的最大值的元素信息,如果設(shè)置了排序方式,則根據(jù)排序方式排列然后再選取定義的排序方式相應(yīng)的最小值和最大值。
?B. 函數(shù)返回的是迭代器(Iterator), 是元素的位置而不是值.
? 如果需要調(diào)用其值大小前面需要*
? 如果需要獲取其位置的信息,可以減去排序起始位置得到此位置信息。
?C. 常用于數(shù)組(int[ ], char[ ]), 字符串string, 容器vetcor等
?D. 函數(shù)頭文件:Algorithm庫(kù)
3. min_element() / max_element()運(yùn)行展示
? A. 數(shù)組運(yùn)行展示
#include<iostream>
#include<algorithm> // 函數(shù)頭文件
using namespace std;
int main(){
int a[3] = {3, 1, 2};
cout << "元素內(nèi)最大值的位置為: " << max_element(a, a + 3) - a << endl;
cout << "元素內(nèi)最大值的值為: " << * max_element(a, a + 3) << endl;
cout << "元素內(nèi)最小值的位置為: " << min_element(a, a + 3) - a << endl;
cout << "元素內(nèi)最小值的值為: " << * min_element(a, a + 3) << endl;
}
? B. 字符串運(yùn)行展示
#include<iostream>
#include<algorithm> // 函數(shù)頭文件
using namespace std;
int main(){
string s = "312";
cout << "元素內(nèi)最大值的位置為: " << max_element(s.begin(), s.end()) - s.begin() << endl;
cout << "元素內(nèi)最大值的值為: " << * max_element(s.begin(), s.end()) << endl;
cout << "元素內(nèi)最小值的位置為: " << min_element(s.begin(), s.end()) - s.begin() << endl;
cout << "元素內(nèi)最小值的值為: " << * min_element(s.begin(), s.end()) << endl;
}
? C. 容器運(yùn)行展示
#include<iostream>
#include<algorithm> // 函數(shù)頭文件
#include<vector>
using namespace std;
int main(){
vector<int> v ={3, 1, 2};
cout << "元素內(nèi)最大值的位置為: " << max_element(v.begin(), v.end()) - v.begin() << endl;
cout << "元素內(nèi)最大值的值為: " << * max_element(v.begin(), v.end()) << endl;
cout << "元素內(nèi)最小值的位置為: " << min_element(v.begin(), v.end()) - v.begin() << endl;
cout << "元素內(nèi)最小值的值為: " << * min_element(v.begin(), v.end()) << endl;
}
? D. 自定義排序文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-636141.html
#include<iostream>
#include<algorithm> // 函數(shù)頭文件
using namespace std;
bool cmp(int x, int y){ //反向排序,值越大則權(quán)重越小
return x > y;
}
int main(){
int a[3] = {3, 1, 2};
cout << "元素內(nèi)最大值的位置為: " << max_element(a, a + 3, cmp) - a << endl;
cout << "元素內(nèi)最大值的值為: " << * max_element(a, a + 3, cmp) << endl;
cout << "元素內(nèi)最小值的位置為: " << min_element(a, a + 3, cmp) - a << endl;
cout << "元素內(nèi)最小值的值為: " << * min_element(a, a + 3, cmp) << endl;
}
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-636141.html
到了這里,關(guān)于Min_element / Max_element 函數(shù)(C/C++)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!