Sorting by integer in a structure contained in a QList or QVector
-
wrote on 5 May 2022, 11:32 last edited by
Hi,
This may be more of a C++ questions as appose to Qt but the is some overlap. I have a structure which is made up of an integer and a QString.
struct myStruct {
int seq;
QString someText;
}
I then add the structure in a QList or QVector (I guess it doesn't make a difference), like so,
QVector<myStruct> myVector;
So now I have a vector of structures and each structure has an integer and QString elements.As I add values to the vector, the seq (integer value) may or may not be in order. I know if I have a QList<int> I can easily sort it. Is there a way that is similar to sort where I can rearrange the order of my structure entries in the vector so they are in order by integer value (seq)? I guess, I can copy the seq into a QList, sort it and then use a for loop through the vector and match the seq between the QList and QVector and rearrange that way but it seems like a complicated convoluted way of doing it.
Thanks.
-
Hi,
This may be more of a C++ questions as appose to Qt but the is some overlap. I have a structure which is made up of an integer and a QString.
struct myStruct {
int seq;
QString someText;
}
I then add the structure in a QList or QVector (I guess it doesn't make a difference), like so,
QVector<myStruct> myVector;
So now I have a vector of structures and each structure has an integer and QString elements.As I add values to the vector, the seq (integer value) may or may not be in order. I know if I have a QList<int> I can easily sort it. Is there a way that is similar to sort where I can rearrange the order of my structure entries in the vector so they are in order by integer value (seq)? I guess, I can copy the seq into a QList, sort it and then use a for loop through the vector and match the seq between the QList and QVector and rearrange that way but it seems like a complicated convoluted way of doing it.
Thanks.
wrote on 5 May 2022, 12:22 last edited by JonB 5 May 2022, 12:23@leinad
Sort QVector of pointers to custom objects shows just your situation. It shows you how to usestd::sort()
on aQVector
, which is what you are expected to do. That example stores/sorts a vector of pointers tostruct
/class
, but you can change it to work on a vector of thestruct
/class
instead of pointers.An older post in this forum, https://forum.qt.io/topic/47037/solved-sorting-possible-on-a-qvector-that-has-a-struct-as-elements, shows the same approach but for
QVector<struct>
like your case. It usesqsort()
because it's old, you should usestd::sort()
. -
wrote on 5 May 2022, 13:19 last edited by
Thank you. I'll take a look
1/3