C++ minmax_element
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版)
QQ 3087438119