美文网首页
如何求数组中的最大值或者最小值

如何求数组中的最大值或者最小值

作者: 沧海梦帆 | 来源:发表于2017-06-22 09:56 被阅读0次

    在c++中经常会遇到求一个数组中的最大值或者最小值,那么如何初始化初始变量min和max呢?
    我经常的做法是,结合实际的场景,设置一个“自以为”很大的数字或者很小的数字来初始化。或者是指定为变量类型所能表示的最大值最小值。对于后一种,c++标准库中已经提供了标准方法。

    #include<limits.h>
    using namespace std;
    void main()
    {
        cout << numeric_limits<int>::max()<< endl;
        /*注意:对于min,在浮点类型中,它返回的是一个最接近0的数字。*/
        cout << numeric_limits<int>::min()<< endl;
        /*返回的是一个“特殊的”正无穷大的数*/
        cout << numeric_limits<int>::infinity() << endl;
        getchar();
    }
    
    #include <iostream>
    #include <limits>
    int main()
    {
        double max = std::numeric_limits<double>::max();
        double inf = std::numeric_limits<double>::infinity();
        //会跳进if语句
        if(inf > max)
            std::cout << inf << " is greater than " << max << '\n';
    }
    
    infinity的返回值infinity的返回值

    其实也可以直接使用标准库中提供的max_element和min_element函数。

        vector<int> a{ 0,9,3,4 };
        auto it = min_element(a.begin(), a.end());
        cout << *it;
    

    相关文章

      网友评论

          本文标题:如何求数组中的最大值或者最小值

          本文链接:https://www.haomeiwen.com/subject/kkvxcxtx.html