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

3

11

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());
Somaliland answered 18/2, 2015 at 9:17 Comment(5)
You have to iterate over the list somehow. You can do it without iterator objects accessing elements by index, but then you'd have to do the actual calculation yourself. Why do you want to do this?Christoffer
Why do you want that without iterator ? (you may still use auto in C++11 to avoid to write QList<double>::iterator)Accidental
Why are you avoiding iteration, is it an optimisation? If so, you could simply keep a track of the minimum and maximum values as items are added to the list and only iterate when an item is removed.Bettyebettzel
Do you want double min = *std::min_element(listVal.begin(), listVal.end()); ? (assuming not empty list).Accidental
That solution is better than @vahancho 's solution because I don't need to sort the list. So I won a line of code.Somaliland
A
28

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());
Accidental answered 18/2, 2015 at 13:31 Comment(0)
N
9

avoiding a round trip of the container:

QList<int> l {2,34,5,2};
auto mm = std::minmax_element(l.begin(), l.end());
qDebug() << *mm.first << *mm.second;
Nez answered 18/2, 2015 at 14:7 Comment(0)
S
5

You can sort your list and take the first and last elements as min and max correspondingly:

qSort(listVal.begin(), listVal.end());
double min = listVal.first();
double max = listVal.last();
Stutsman answered 18/2, 2015 at 9:25 Comment(2)
Note that complexity is now n log(n) instead of n.Accidental
more computational complexity, but very straightforward solution to meBurkes

© 2022 - 2024 — McMap. All rights reserved.