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

前端 未结 7 1377
予麋鹿
予麋鹿 2021-02-08 00:05

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:34

    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;
        }
    }
    

提交回复
热议问题