std::pair
(pair
对)template< class ForwardIt >
std::pair<ForwardIt,ForwardIt>
minmax_element( ForwardIt first, ForwardIt last );
minmax_element
,先是 min
,再 max
,所以,返回的类中的数据成员 first
对应着最小值,second
对应着最大值。template<class ForwardIt, class Compare>
std::pair<ForwardIt, ForwardIt>
minmax_element(ForwardIt first, ForwardIt last, Compare comp)
{
auto min = first, max = first;
if (first == last || ++first == last)
return {min, max};
if (comp(*first, *min)) {
min = first;
} else {
max = first;
}
while (++first != last) {
auto i = first;
if (++first == last) {
if (comp(*i, *min)) min = i;
else if (!(comp(*i, *max))) max = i;
break;
} else {
if (comp(*first, *i)) {
if (comp(*first, *min)) min = first;
if (!(comp(*i, *max))) max = i;
} else {
if (comp(*i, *min)) min = i;
if (!(comp(*first, *max))) max = first;
}
}
}
return {min, max};
}
#include
int main() {
std::vector<int> v = { 1, 2, 5, 4, 100, 0, -199, 33 };
auto result = std::minmax_element(v.begin(), v.end());
// 输出首次出现的最小元素
std::cout << "min element is: " << *result.first << '\n';
// 输出首次出现的最大元素
std::cout << "max element is: " << *result.second << '\n';
return 0;
}
/*
// 官网例子
#include
#include
int main() {
const auto v = { 3, 9, 1, 4, 2, 5, 9 };
auto pStart = begin(v);
auto pEnd = end(v);
const auto result = std::minmax_element(begin(v), end(v));
std::cout << "min = " << *result.first << ", max = " << *result.second << '\n';
return 0;
}
*/
C++17
中的 min_element
, 返回迭代器位置, 复杂度为 O(n)
template<class ForwardIt>
ForwardIt min_element(ForwardIt first, ForwardIt last)
{
if (first == last) return last;
ForwardIt smallest = first;
++first;
for (; first != last; ++first) {
if (*first < *smallest) {
smallest = first;
}
}
return smallest;
}
#include
#include
#include
int main()
{
std::vector<int> v{3, 1, 4, 1, 5, 9};
std::vector<int>::iterator result = std::min_element(v.begin(), v.end());
std::cout << "min element at: " << std::distance(v.begin(), result) << std::endl;
std::cout << "min value is: " << *result << std::endl; // 1
return 0;
}
C++17
中的 max_element
, 返回迭代器位置, 复杂度为 O(n)
template<class ForwardIt>
ForwardIt max_element(ForwardIt first, ForwardIt last)
{
if (first == last) return last;
ForwardIt largest = first;
++first;
for (; first != last; ++first) {
if (*largest < *first) {
largest = first;
}
}
return largest;
}
#include
#include
#include
int main()
{
std::vector<int> v{3, 1, 4, 1, 5, 9};
std::vector<int>::iterator result = std::max_element(v.begin(), v.end());
std::cout << "max element at: " << std::distance(v.begin(), result) << std::endl;
std::cout << "max value is: " << *result << std::endl; // 9
return 0;
}
https://en.cppreference.com/w/cpp/algorithm