Find index of QVector by comparing an item
-
wrote on 8 Aug 2010, 04:06 last edited by
Hi,
I want to compare a item in a QVector and that will return index.
Ex. QVector {20,45,57,89} [0,1,2,3]
for value 46 it should say 2
for value 21 to 45 it should return 1
I can do this by using some loop conditions. But I want to know is there any inbuilt function for this.
-
wrote on 8 Aug 2010, 08:55 last edited by
-
wrote on 8 Aug 2010, 10:26 last edited by
This is not my problem. I know that how to find index of an item .
My Question is to find index of item which is in range not exactly there.
Like 46 is nowhere still it returns 2 and not -1 like above func.
Hope it clears me more.
-
wrote on 8 Aug 2010, 10:27 last edited by
Consider any type of container like QVector or QList any item which can solve my problem.
-
wrote on 8 Aug 2010, 10:47 last edited by
Since this is applicable only to sorted vectors, it would be strange if there existed a method like that in a QVector.
You can easily implement it via a binary search.
-
wrote on 8 Aug 2010, 10:54 last edited by
yea that's what I was thinking i.e binary search but I was looking for any easy solution(s).
BS is in qt.
Link is "Binary search in QT":http://doc.trolltech.com/qq/qq15-qalgorithms.html
-
wrote on 8 Aug 2010, 16:38 last edited by
Well, I don't think you'll be able to use the built-in BS. (you are not looking for an exact match).
Alternatively, you can go wild :) and implement a Range class and overload some operators... but I think it would be too much hassle for something like this.
-
wrote on 9 Aug 2010, 07:30 last edited by
Agreed
I'm doing with core c++.
Will post solution here for other guys.
-
wrote on 9 Aug 2010, 15:41 last edited by
Such a list has been implemented by a troll before and is available here
http://qt.gitorious.org/qt-labs/itemviews-ng/blobs/master/src/qsectionspans_p.h
-
wrote on 24 Aug 2010, 08:18 last edited by
I think what you are looking for is qLowerBound (or qUpperBound). It does a binary search, and returns the position where the item should be inserted, regardless of if the item is found or not.
-
wrote on 29 Aug 2010, 09:55 last edited by
Just want to add that QMap has upperBound and lowerBound as methods directly; which is a bit nicer to me than using a global method ;)
-
wrote on 21 May 2011, 05:50 last edited by
QMap is perfect solution in this case.
I'm little late .... :)
Thanks guy!