I am trying to reverse iterate an array of strings. The code below is working perfectly
QStringList aCodes;
aCodes<<"1"<<"2"<<"3"<<"4";
QStringList::iterator its;
for(its = aCodes.end()-1;its != aCodes.begin()-1;--its)
{
qDebug()<<*its;
}
The code below is also working, but its is printing the last three strings only.
for(its = aCodes.end()-1;its != aCodes.begin();--its)
{
qDebug()<<*its;
}
CodePudding user response:
QStringList inherits QList which provides STL-like iterators, meaning it supports reverse_iterator.
QStringList::reverse_iterator its;
for(its = aCodes.rbegin(); its != aCodes.rend(); its)
{
qDebug() << *its;
}
CodePudding user response:
You can avoid a raw for loop altogether with std::for_each if you #include <algorithm>:
#include <algorithm>
std::for_each(std::rbegin(aCodes), std::rend(aCodes), [&](auto &ac) { qDebug() << ac; }
For more info, see cppreference on reverse iterators.
