Neeraj Shukla
Neeraj Shukla

Reputation: 29

How to Reverse iterate an array in c++?

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;
} 

Upvotes: 1

Views: 874

Answers (3)

paddy
paddy

Reputation: 63471

QStringList inherits QList which provides STL-like iterators, meaning it supports reverse_iterator. Note this is only available since Qt 5.6.

// Iterate in reverse with QList<T>::reverse_iterator (since Qt 5.6)
QStringList::reverse_iterator its;
for(its = aCodes.rbegin(); its != aCodes.rend(); ++its)
{
    qDebug() << *its;
}

Although not really an issue here, you should familiarize yourself with the iterator sharing problem when using Qt containers and STL-like iterators.

In older versions of Qt that don't support reverse_iterator, you can at least use the bidirectional iterator as follows:

// Iterate in reverse with QList<T>::iterator
if (!aCodes.isEmpty())
{
    QStringList::iterator its = aCodes.end();
    do {
        --its;
        qDebug() << *its;
    } while (its != aCodes.begin());
}

Alternatively, you can use index-based iteration, which QList is designed for.

// Iterate in reverse with indices
for (int i = aCodes.size() - 1; i >= 0; --i)
{
    qDebug() << aCodes[i];
}

Upvotes: 7

you can try to use an vector of QString like this

std::vector<QString> v{1, 2, 3, 4, 5};
for (std::vector<QString>::reverse_iterator it = v.rbegin(); it != v.rend(); ++it)
{
    cout << *it;
} // prints 54321

Upvotes: 2

Dimitrije Kostic
Dimitrije Kostic

Reputation: 305

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.

Upvotes: 0

Related Questions