Issue
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?
Solution
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;
result.reserve( in.size() ); // reserve is new in Qt 4.7
std::reverse_copy( in.begin(), in.end(), std::back_inserter( result ) );
return result;
}
EDIT 2015-07-21: Obviously (or maybe not), if you want a one-liner (and people seem to prefer that, looking at the relative upvotes of different answers after five years) and you have a non-const
list
the above collapses to
std::reverse(list.begin(), list.end());
But I guess the index fiddling stuff is better for job security 🙂
Answered By – Marc Mutz – mmutz
Answer Checked By – Willingham (BugsFixing Volunteer)