Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a QList?

Tags:

qt

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?

like image 762
mpen Avatar asked Aug 27 '09 06:08

mpen


2 Answers

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 :)

like image 186
Marc Mutz - mmutz Avatar answered Sep 22 '22 09:09

Marc Mutz - mmutz


Reverse your QList with a single line:

for(int k = 0; k < (list.size()/2); k++) list.swap(k,list.size()-(1+k)); 
like image 23
Marc Jentsch Avatar answered Sep 18 '22 09:09

Marc Jentsch