首页 > 编程语言 > 详细

C++ minmax_element

时间:2020-01-02 22:26:32      阅读:109      评论:0      收藏:0      [点我收藏+]

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版)

C++ minmax_element

原文:https://www.cnblogs.com/herd/p/12141921.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!