4.2.1.  QStringList and iteration

[ fromfile: iterators.xml id: qstringlist ]

Example 4.1. src/containers/lists/lists-examples.cpp

#include <QStringList>
#include <QDebug>

/* Some simple examples using QStringList, split and join */

int main() {

    QString winter = "December, January, February";
    QString spring = "March, April, May";
    QString summer = "June, July, August";
    QString fall = "September, October, November";

    QStringList list;
    list << winter;                            1
    list += spring;                            2
    list.append(summer);                       3
    list << fall;

    qDebug() << "The Spring months are: " << list[1] ;


    QString allmonths = list.join(", ");       4
    qDebug() << allmonths;

    QStringList list2 = allmonths.split(", "); 5

    Q_ASSERT(list2.size() == 12);              6

    foreach (const QString &str, list) {       7
        qDebug() << QString(" [%1] ").arg(str);
    }

    for (QStringList::iterator it = list.begin();
         it != list.end(); ++it) {             8
        QString current = *it;                 9
        qDebug() << "[[" << current << "]]";
    }

    QListIterator<QString> itr (list2);        10
    while (itr.hasNext()) {                    11
        QString current = itr.next();
        qDebug() << "{" <<  current << "}";
    }
    return 0;
}

1

Append operator 1.

2

Append operator 2.

3

Append member function.

4

From list to string - join with a ", " delimiter.

5

Split is the opposite of join. Each month will have its own element.

6

Q_ASSERTions abort the program if the condition is not satisfied.

7

Qt foreach loop - similar to Perl/Python and Java 1.5 style for loops.

8

C++ STL-style iteration.

9

Pointer-style dereference.

10

Java 1.2 style Iterator.

11

Java Iterators point between elements.


Following is the output of Example 4.1:

src/containers/lists> ./lists
The Spring months are:  "March, April, May"
"December, January, February, March, April, May, June, July, August, September, October, November"
" [December, January, February] "
" [March, April, May] "
" [June, July, August] "
" [September, October, November] "
[[ "December, January, February" ]]
[[ "March, April, May" ]]
[[ "June, July, August" ]]
[[ "September, October, November" ]]
{ "December" }
{ "January" }
{ "February" }
{ "March" }
{ "April" }
{ "May" }
{ "June" }
{ "July" }
{ "August" }
{ "September" }
{ "October" }
{ "November" }
/src/containers/lists>


[24] In fact, QStringList is derived from QList<QString> so it inherits QList's entire public interface. We discuss derivation and inheritance in (Chapter 6).