PDA

View Full Version : Max and min from QVector<QPoint>



awpitt13
13th February 2012, 19:07
Hello,

I have an array of QVector <QPoint> and I'm trying to find the maximum and minimum of each x and y. (trying to get X max, X min, Y max, Y min). Is there a clean way of going about this? I was looking at QSort but I'm not sure how to seperate the QPoint container into its x and y.

Thank you in advance for any advice you can offer.

norobro
13th February 2012, 22:00
See the overloaded qSort function here (http://doc.qt.nokia.com/4.7/qtalgorithms.html#qSort). You will obviously have to sort twice so you need to define one function comparing the x values and another comparing the y values.

ChrisW67
13th February 2012, 23:09
Here are two other options:


#include <limits>

QVector<QPoint> array;
array << QPoint(-1, 5) << QPoint(-2, 0) << QPoint(0, 3);

Q_ASSERT(array.size() > 0);
int xMin = std::numeric_limits<int>::max(); // everything is <= this
int xMax = std::numeric_limits<int>::min(); // everything is >= this
int yMin = std::numeric_limits<int>::max();
int yMax = std::numeric_limits<int>::min();
foreach (QPoint p, array) {
xMin = qMin(xMin, p.x());
xMax = qMax(xMax, p.x());
yMin = qMin(yMin, p.y());
yMax = qMax(yMax, p.y());
}
qDebug() << xMin << xMax << yMin << yMax;

or


QPolygon poly(array);
QRect brect = poly.boundingRect();

qDebug() << brect.left() << brect.right() << brect.top() << brect.bottom(); // note the smallest y is the top of the box not the bottom

norobro
14th February 2012, 00:31
@ChrisW67: The QPolygon::boundingRect() solution is a good one. Hadn't thought of that.

@awpitt13: The qSort code:
#include <QtCore>

bool xLessThan(const QPoint &p1, const QPoint &p2){ return p1.x()<p2.x();}

bool yLessThan(const QPoint &p1, const QPoint &p2){ return p1.y()<p2.y();}

int main(){
srand(time(NULL));
QVector<QPoint> vec;
for(int i=0; i<5; i++)
vec.append(QPoint(rand() % 100, rand() % 100));
qDebug() << vec;
qSort(vec.begin(),vec.end(),xLessThan);
qDebug() << "Min X=" << vec.first().x() <<"\tMax X="<< vec.last().x();
qSort(vec.begin(),vec.end(),yLessThan);
qDebug() << "Min Y="<< vec.first().y()<<"\tMax Y=" << vec.last().y();
return 0;
}

ChrisW67
14th February 2012, 01:18
I expect that a bounding box is what awpitt13 is ultimately trying to determine.