c++qtqlist

How to get the min and the max of a QList in Qt without using any iterator?


Is there a way to get the min and the max of a QList in Qt without using any iterator ?

Here is the code using iterator :

QList<double>::iterator min = std::min_element(listVal.begin(), listVal.end());
QList<double>::iterator max = std::max_element(listVal.begin(), listVal.end());

Solution

  • If you don't want iterator as result but directly the value, you may deference the result directly:

    //assert(!listVal.empty());
    double min = *std::min_element(listVal.begin(), listVal.end());
    double max = *std::max_element(listVal.begin(), listVal.end());
    

    And in C++17, with structure binding:

    //assert(!listVal.empty());
    auto [min, max] = *std::minmax_element(listVal.begin(), listVal.end());