C++ minmax_element 最大值 最小值
algostuff.hpp
#ifndef ALGOSTUFF_HPP
#define ALGOSTUFF_HPP
#include <array>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>
#include <iostream>
#include <string>
//集合中添加元素
template <typename T>
inline void INSERT_ELEMENTS(T& coll, int first, int last)
{
for (int i = first; i <= last; ++i)
{
coll.insert(coll.end(), i);
}
}
//输出集合中的元素
template <typename T>
inline void PRINT_ELEMENTS(const T& coll, const std::string & optcstr = "")
{
std::cout << optcstr;
for (auto elem : coll)
{
std::cout << elem << " ";
}
std::cout << std::endl;
}
//输出Map中的元素
template<typename T>
inline void PRINT_MAPPED_ELEMENTS(const T& coll, const std::string& optcstr = "")
{
std::cout << optcstr;
for (auto elem : coll)
{
std::cout << "[" << elem.first << "," << elem.second << "] ";
}
std::cout << std::endl;
}
#endif // !ALGOSTUFF_HPP
minmax1.cpp
#include "algostuff.hpp"
using namespace std;
bool absLess(int elem1,int elem2)
{
return abs(elem1) < abs(elem2);
}
int main()
{
deque<int> deq1;
INSERT_ELEMENTS(deq1, 2, 6);
INSERT_ELEMENTS(deq1, -3, 6);
PRINT_ELEMENTS(deq1);
cout << "min element: " << *min_element(deq1.cbegin(),deq1.cend()) << endl;
cout << "max element: " << *max_element(deq1.cbegin(),deq1.cend()) << endl;
auto m1 = minmax_element(deq1.cbegin(),deq1.cend());
cout << "min: " << *(m1.first) << endl;
cout << "max: " << *(m1.second) << endl;
cout << "distance: " << distance(m1.first,m1.second) << endl;
cout << "minimum of absolute values: " << *min_element(deq1.cbegin(),deq1.cend(),absLess) << endl;
cout << "maximum of absolute values: " << *max_element(deq1.cbegin(), deq1.cend(), absLess) << endl;
system("pause");
return 0;
}
2 3 4 5 6 -3 -2 -1 0 1 2 3 4 5 6
min element: -3
max element: 6
min: -3
max: 6
distance: 9
minimum of absolute values: 0
maximum of absolute values: 6
请按任意键继续. . .
代码参考:C++标准库(第2版)
原文链接: https://www.cnblogs.com/herd/p/12141921.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/191302
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!