Program to find largest and smallest among 5 numbers without using array

前端 未结 15 2277
遇见更好的自我
遇见更好的自我 2021-01-06 07:25

Yesterday I went for an interview where I have been asked to create a program to find largest and smallest among 5 numbers without using array.

I know how to create

15条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-06 08:01

    Works for any number of numbers taken from standard input:

    #include 
    #include 
    #include 
    
    int main()
    {
        std::istream_iterator it_begin(std::cin), it_end;
        auto p = std::minmax_element(it_begin, it_end);
        if (p.first != it_end)
            std::cout << "min: " << *p.first << " max: " << *p.second;
    }
    

    Disclaimer:
    Technicaly, this isn't required to work by C++ standard. The minimum iterator category required for minmax_element is ForwardIterator which stream iterators are not. Once an input iterator is dereferenced or incremented, its copies are no longer guaranteed to be dereferenceable or comparable to other iterators. It Works On My MachineTM. :)

提交回复
热议问题