PDA

View Full Version : Search value in QList



pelaoqlo
6th February 2019, 14:02
Hi everyone :D

I'm programming in qt, with qt 5 and i have a dude. I have a QList<double> list; and this list list contain much values.
Example:


(7.41043, 7.6002, 7.41904, 7.41041, 7.59567, 7.80702, 7.9873, 7.80707, 7.78752, 7.967, 7.78653, 7.96694, 7.40598, 7.40597, 7.5947, 7.76546, 7.94506, 7.82004, 8.0137, 7.99947)


How can search in the list the value most close to 0 and return this? and know the position in the list? :(

Ginsengelf
6th February 2019, 15:20
Hi, if you only have positive values then use std::min_element.

Ginsengelf

Lesiok
6th February 2019, 15:21
1. This is QList<double> not QList<int>.
2. If you can not sort the list then you have to check each element and choose the one for which abs (value) is the smallest. If you only have positive values, you choose the smallest value (you do not need abs). Something like this (for positive only value) :
double s_value = list.at(0);
int s_index=0;
for(int i=1; i < list.size();i++)
{
if(list.at(i) < s_value)
{
s_value = list.at(i);
s_index = i;
}
}

pelaoqlo
6th February 2019, 17:11
1. This is QList<double> not QList<int>.
2. If you can not sort the list then you have to check each element and choose the one for which abs (value) is the smallest. If you only have positive values, you choose the smallest value (you do not need abs). Something like this (for positive only value) :
double s_value = list.at(0);
int s_index=0;
for(int i=1; i < list.size();i++)
{
if(list.at(i) < s_value)
{
s_value = list.at(i);
s_index = i;
}
}


1. Typing error, sorry.
2. It's work, thanks. I had the doubt of how to get the values from the list, do not observe the method const T &QList::at(int i) const (http://doc.qt.io/qt-5/qlist.html#at) at the documentation, my mistake. Thank you very much for the reply:D

anda_skoa
7th February 2019, 11:51
Hi, if you only have positive values then use std::min_element.


Yes, definitely std::min_element (https://en.cppreference.com/w/cpp/algorithm/min_element).

If there are negative values then with a compare function that takes the abs() for comparison

Cheers,
_