I see qCopy, and qCopybackward but neither seems to let me make a copy in reverse order. qCopybackward
only copies it in reverse order, but keeps the darn elements in the same order! All I want to do is return a copy of the list in reverse order. There has to be a function for that, right?
views:
797answers:
5For standard library lists it would look like this
std::list<X> result;
std::copy(list.rbegin(), list.rend(), result.back_inserter());
Unfortunately, Qt doesn't have rbegin and rend functions that return reverse iterators (the ones that go from the end of the container to its begnning). You may write them, or you can just write copying function on your own -- reversing a list is a nice excersize. Or you can note that QList is actually an array, what makes writing such a function trivial. Or you can convert the list to std::list, and use rbegin and rend. Choose whatever you like.
If you don't like the QTL, just use the STL. They might not have a Qt-ish API, but the STL API is rock-stable :) That said, qCopyBackward
is just std::copy_backward
, so at least they're consistent.
Answering your question:
template <typename T>
QList<T> reversed( const QList<T> & in ) {
QList<T> result;
std::reverse_copy( in.begin(), in.end(), std::back_inserter( result ) );
return result;
}
Reversing a QList is going to be O(n) however you do it, since QList isn't guaranteed to have its data stored contiguously in memory (unlike QVector). You might consider just traversing the list in backwards order where you need to, or use something like a QStack which lets you retrieve the elements in the opposite order they were added.
You can use the Java style iterator. Complete example here (http://doc.trolltech.com/2.3/collection.html). Look for the word "reverse".
QList<int> list; // initial list
list << 1;
list << 2;
list << 3;
QList<int> rlist; // reverse list+
QListIterator<int> it(list);
for ( it.toLast(); it.current(); --it) ) {
rlist << it.current();
}