Joshua Grauman schreef op 19.11.2013 21:26: > I fairly often find myself wanting to sort a bit of data. Imagine I > have a > few QList<int>'s a QStringList's and that they correspond like a > database > table so that I always append to all the lists together with data for > one > row. Something like: > > QList<int> age, height; > QStringList firstname, lastname; > while(data) > { > age.append(getData1()); > height.append(getData2()); > firstname.append(getData3()); > lastname.append(getData4()); > } > > Now what if I want to sort all that data, (say by age) so that I can > print > out all the first and last names in order according to age.
I think your problem is in your data structure. Instead of using separate containers for each of the fields, you should use a single container with all of the fields: struct Person { int age; int height; QString firstName; QString lastName; } QList<Person> persons; while(data) { Person person; person.age = getData1(); person.height = getData2(); person.firstName = getData3(); person.lastName = getData4(); persons.append(person); } Now, you can easily sort the persons list itself by using qSort with a comparison function for the field you want to sort on, or keep track of the order by using a QMap<key, int> using the index into the persons list as the value of your map. Alternatively, look into Boost.MultiIndex. André > > I've tried different ways of doing this, but they all seem a bit > contrived. The best I've come up with is to have another QMap<int, int> > that maps the sorting order to the indices like: > > QList<int> age, height; > QStringList firstname, lastname; > QMap<int, int> order; > while(data) > { > age.append(getData1()); > height.append(getData2()); > firstname.append(getData3()); > lastname.append(getData4()); > order[age.last()] = age.size()-1; > } > > QList<int> orderedIndices = order.values(); > > for(int i=0; i<orderedIndices.size(); i++) > { > print(firstname[orderedIndices[i]], lastname[orderedIndices[i]]); > } > > It's not too bad. I'm not worried about performance, most of the time > these are just small amounts of data that don't warrant creating a new > class to handle, or creating a database for. I'm just wondering if > anyone > has a cleaner way of handling this? What do you do for these types of > situations? > > Josh > _______________________________________________ > Interest mailing list > Interest@qt-project.org > http://lists.qt-project.org/mailman/listinfo/interest _______________________________________________ Interest mailing list Interest@qt-project.org http://lists.qt-project.org/mailman/listinfo/interest