How to workaround the inconsistent definition of numeric_limits::min()?

前端 未结 7 771
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 23:50

The numeric_limits traits is supposed to be a general way of obtaining various type infomation, to be able to do things like

template
T min(con         


        
7条回答
  •  清酒与你
    2021-02-08 00:26

    The definition of the smallest value for an empty vector can be argued. If the vector is empty then there is no smallest element.

    Prefer to use std::min_element instead:

    int main()
    {
        std::vector v;
        std::generate_n(std::back_inserter(v), 1000, std::rand);
    
        std::vector::iterator it  = std::min_element(v.begin(), v.end());
        if (it == v.end())
        {
            std::cout << "There is no smallest element" << std::endl;
        }
        else
        {
            std::cout << "The smallest element is " << *it << std::endl;
        }
    }
    

提交回复
热议问题