PDA

View Full Version : Copying an QList into a new, sorted QList.



Thomas Wrobel
11th January 2010, 18:15
I wish to have a function return a sorted version of a QList. (The QList is of a custom-type called an "arblip")

I have two ideas how to do this;

a) Either I could copy the whole array, and use qSort, returning the copy.
or
b) Iterate though the items in one list, copying them into a new list.

I'm not sure which is the better approach, and having tried both, I can get neither to work. I suspect its because I'm a neewbie and not understanding how to clone an array, or am getting my pointers mixed up, or both.

My attempt at using qsort was basicaly;



bool compareNames(arblip& s1,arblip& s2)
{
QDateTime temp1=s1.getLastUpdateTime();
QDateTime temp2=s2.getLastUpdateTime();

return (temp1<temp2);
}

QList<arblip> arbliparray::getallblips_orderedbytimestamp(){

//create temp list;
QList <arblip> orderedarray;

orderedarray=arblipStore;
qSort(orderedarray.begin(),orderedarray.end(),comp areNames);

return orderedarray;
}

Which compiled, but once that part of the code was triggered, exited with a "1073741819" code.
I suspected its probably that = statement.

I had a similar issue with trying method b, this time crashing when I tried to assign a arblip object from one list to another.

...arblip currentblip = *arblip_iterator;
orderedarray.append(currentblip); ...


I think my problem is not knowing how to make a complete copy of an object, rather then merely creating a new pointer to it?
I want to return a ordered copy of the list, and for the original list to remain private and untouched.

bood
11th January 2010, 18:28
the = should be fine here
I think the problem lies somewhere else
but you should paste more code to see...
I suggest you use qDebug to confirm which statement has caused the crash exactly first

squidge
11th January 2010, 18:53
Is there a reason you can't use the tried and tested STL sort? No copy needed, as it'll work on the original, unless you want the copy, of course.

Thomas Wrobel
11th January 2010, 19:27
Well, in this case I do want a copy, but I'll bare that in mind in future.


the = should be fine here
I think the problem lies somewhere else
but you should paste more code to see...
I suggest you use qDebug to confirm which statement has caused the crash exactly first

Thanks! I was too busy getting confused with the aspects of the language alien to me, I missed a very stupid mistake earlier.
I was calling the function twice from within a for statement (one for a constBegin, the other for a constEnd). It was no wonder it was crashing.
Simply assigning it to use one copy and it all works.