View Full Version : auto-sorted qtl container
tuli
5th March 2013, 21:04
I am using a std::set<int> to keep a list of sorted ints. The set is automatically sorted, so i can add a value at any time, and the set will be reordered.
The QTL equivalent (?) however, is QHash-based, which i would seem unnecessary here. The items are also not sorted.
So what's the QTL equivalence of the STL set<int> ?
std::set<int> sss;
sss.insert(0x100);
sss.insert(0x10);
sss.insert(0);
sss.insert(0x1000);
//sss -> 0,0x10,0x100,0x1000
QSet<int> aaa;
aaa.insert(0x100);
aaa.insert(0x10);
aaa.insert(0);
aaa.insert(0x1000);
//aaa -> 0x100,0x10,0,0x1000
wysota
5th March 2013, 21:42
Hmmm.... QSet?
amleto
5th March 2013, 21:48
Hmmm.... QSet?
That is not ordered either
wysota
5th March 2013, 22:27
A set is not ordered. An ordered set is a list.
ChrisW67
5th March 2013, 22:49
A std::set is ordered and contains no duplicates (unlike a list). QSet, on the other hand, does not preserve order: it is closer to the mathematical notion of a set.
Using QMap keys only would be the closest match if uniqueness and order is important.
QMap<int,int> sss;
sss.insert(0x100, 0); // value is irrelevant
sss.insert(0x10, 0);
sss.insert(0, 0);
sss.insert(0x1000, 0);
qDebug() << sss.keys();
// (0, 16, 256, 4096)
If uniqueness is not a requirement then a simple QList that you sort before access is a good match.
wysota
5th March 2013, 23:29
You can always use this simple scheme:
QList<int> list;
int valueToInsert = 42;
QList::iterator iter = qLowerBound(list.begin(), list.end(), valueToInsert);
if(iter == list.end() || *iter != valueToInsert) list.insert(iter, valueToInsert);
tuli
7th March 2013, 13:31
Kay, so taht's not possible. Using QMap with a dummy .data field seems a little too messy to me, using QList<> as suggested by wysota is ofcourse possible.
Thanks all, guess i'll go with that.
Lil follow-up problem:
I can only get const References to the items contained in the list. Why?
MyClass& LeFunc(...)
{
QList<MyClass> list;
...
Q_FOREACH(MyClass& i, list) //error C2440: 'initializing' : cannot convert from 'const MyClass' to 'MyClass &'
{
if(i.thisisit())
return i;
}
...
}
wysota
7th March 2013, 13:34
Because foreach makes a copy of the container. It's for immutable loops only.
tuli
7th March 2013, 13:55
Makes snese. :)
Although this doesnt work either:
for(QList<MyClass>::iterator it=list.begin(); it != list.end(); ++it) //error C2440: 'initializing' : cannot convert from 'QList<T>::const_iterator' to 'QList<T>::iterator'
{
if(it->thisisit())
return *it;
}
wysota
7th March 2013, 14:05
Apparently your "list" is const. Why do you insist on using a non-const iterator here?
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.