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

user4473281 picture user4473281 · Feb 18, 2015 · Viewed 21.6k times · Source

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());

Answer

Jarod42 picture Jarod42 · Feb 18, 2015

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());