工作中往往有这样的场景:选出一个容器,或是范围内的最大值、最大元素、最小值和最小元素。很普通的做法就是,我们用一个for循环进行遍历,然后达到我们的效果。
其实stl的算法中就提供了一些关于最大和最小的操作,我们往往忽略他们。
这篇博客也是关于C++11中新增加的算法最后一次博客了。
还是先介绍几个在C++11之前就存在的,但是与本博客息息相关的算法。
首先是:
min和max
由于很简单,所以直接上代码:
#include <iostream> // std::cout
#include <algorithm> // std::min
int main () {
std::cout << "min(1,2)==" << std::min(1,2) << '\n';
std::cout << "min(2,1)==" << std::min(2,1) << '\n';
std::cout << "min('a','z')==" << std::min('a','z') << '\n';
std::cout << "min(3.14,2.72)==" << std::min(3.14,2.72) << '\n';
std::cout << "max(1,2)==" << std::max(1,2) << '\n';
std::cout << "max(2,1)==" << std::max(2,1) << '\n';
std::cout << "max('a','z')==" << std::max('a','z') << '\n';
std::cout << "max(3.14,2.73)==" << std::max(3.14,2.73) << '\n';
return 0;
}
接下来是C++11新增的:
minmax
我们从字面上就可以有所把握。
返回的是一个pair 。
Returns a pair with the smallest of a and b as first element, and the largest as second. If both are equivalent, the function returns make_pair(a,b).
看代码:
#include <iostream> // std::cout
#include <algorithm> // std::minmax
int main () {
auto result = std::minmax({1,2,3,4,5});
std::cout << "minmax({1,2,3,4,5}): ";
std::cout << result.first << ' ' << result.second << '\n';
return 0;
}
至此,你肯定意犹未尽,好像欠缺了点什么。上面提到的min和max没有用于range。
min_element和max_element
#include <iostream> // std::cout
#include <algorithm> // std::min_element, std::max_element
bool myfn(int i, int j) { return i<j; }
struct myclass {
bool operator() (int i,int j) { return i<j; }
} myobj;
int main () {
int myints[] = {3,7,2,5,6,4,9};
// using default comparison:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7) << '\n';
// using function myfn as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myfn) << '\n';
// using object myobj as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myobj) << '\n';
return 0;
}
效仿minmax,同样是C++11新增的内容:
minmax_element
Returns a pair with an iterator pointing to the element with the smallest value in the range [first,last) as first element, and the largest as second.
#include <iostream> // std::cout
#include <algorithm> // std::minmax_element
#include <array> // std::array
int main () {
std::array<int,7> foo {3,7,2,9,5,8,6};
auto result = std::minmax_element (foo.begin(),foo.end());
// print result:
std::cout << "min is " << *result.first;
std::cout << ", at position " << (result.first-foo.begin()) << '\n';
std::cout << "max is " << *result.second;
std::cout << ", at position " << (result.second-foo.begin()) << '\n';
return 0;
}
以上代码出自:
http://www.cplusplus.com/