c++中求字符串数组的min/max
生活随笔
收集整理的這篇文章主要介紹了
c++中求字符串数组的min/max
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、函數:(作用:返回容器中最小值和最大值。)
min_element()
max_element
max_element(first,end,cmp);其中cmp為可選擇參數!
第三個參數cmp可寫可不寫, max_element() 和 min_element() 默認是從小到大排列,然后 max_element() 輸出最后一個值, min_element() 輸出第一個值,但是如果自定義的 cmp 函數寫的是從大到小排列,那么會導致 max_element() 和min_element() 的兩個結果是對調的
可以用于 容器 vector ?,也可以用于數組 int arr[4] 或者string arr[4]?
2、示例?
#include<iostream>
#include<string>
#include<vector>
using namespace std;
#include<algorithm>bool cmp(string &s1, string &s2)
{return s1.size() > s2.size();
}int main()
{//返回的是迭代器vector<string>v ;v.push_back("s");v.push_back("ste");v.push_back("ste4dfy");//求min,max的字符串string min1 = *min_element(v.begin(), v.end());cout << "min1=" << min1 << endl;string max1 = *max_element(v.begin(), v.end());cout << "max1=" << max1 << endl;//求字符串min,max的尺寸int min = min_element(v.begin(), v.end())->size();cout << "min=" << min << endl;int max = max_element(v.begin(), v.end())->size();cout << "max=" << max << endl;//重載string max2 = *max_element(v.begin(), v.end(),cmp);cout << "max2=" << max2 << endl;system("pause");return 0;
}
?
總結
以上是生活随笔為你收集整理的c++中求字符串数组的min/max的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 回文数:给你一个整数 x ,如果 x 是
- 下一篇: 利用指针打印数组