Topics Runtime Error?
1) What is the best way to store a group of items? Containers 2) How can we step through all the items? & Iterators 3) What Qt classes store items?
Ch 4
03/02/12 CMPT 212 Slides #8 © Dr. B. Fraser 1 03/02/12 2
Generic Containers QList
$ Generic Containers $ QList
Templates: work with any (one) type of data. Declare to hold a specific type: QList
03/02/12 3 03/02/12 http://developer.qt.nokia.com/doc/qt-4.8/qlist.html 4 QList example int main(int argc, char *argv[]) QList
Direct Access Iterator Pattern
$ Direct Access $ Iterator Pattern Definition: Use a loop to access elements "directly". The iterator pattern provides a way to access the for (int i = 0; i < heros.size(); i++) { elements of an aggregate object sequentially.. cout << heros[i] << endl; } $ Iterators work for all collections (trees, maps, list, ...) $ 3 styles: C++ std iterator, Java Iterator, Qt's foreach $ Iterators Collection of Items: for (QList
C++ Standard Library Style Iterator Java Style Iterator (for Qt in C++) Define: Define & Init: Start: pizzas.begin() End: !itr.hasNext() // Setup the list... End: pizzas.end() Get & Advance: Pizza lunch = Advance: QList
Qt's For Each
Qt's foreach loop Iterator is.. Implemented at compile time by the Meta Object Compiler (MOC) // Setup the list... QList
03/02/12 11 03/02/12 12 QStringList QMap
$ QMap is an $ Special list for QStrings: QList
$ // Populate with data to change a QString into a QStringList students[200012345] = "Dr. Evil"; $ to merge a QStringList into a QString students[100110101] = "Ms. Binary"; students[999999998] = "Mr. Achiever"; Example: Q_ASSERT(students.size() == 3); QString str = "one, two, three"; // Mwahahahah Q_ASSERT(students[100110101] == "Ms. Binary"); Q_ASSERT(students.contains(999999998) == true); QStringList lst = str.split(", "); // Has 3 elements Q_ASSERT(students.contains(1) == false); QString together = lst.join(" ---> "); // One string. // Change the value at a key. Q_ASSERT(together == "one ---> two ---> three"); students[999999998] = "I. R. Best"; 03/02/12 13 03/02/12 14
Checking items QMap and Iterators $ Data is stored.. $ Be careful using [] with QMap // Java style iterator // Create & populate map: Use daMap.contains(key) to.. QMap
$ Some details on challenges with QMap: $ Generic containers use templates to store any one key type must work with.. Classes can overload < (ex: QString) type of value. Value must be assignable (or won't compile): $ QList used to store a series of elements. $ default constructor $ Iterators abstract the notion of iteration into a class. $ copy constructor There are 3 types of iterators supported by Qt. $ assignment operator $ QStringList useful for working with strings. Work-around is to use a pointer. $ QMap stores (key, value) pairs. Ex: If Pizza is not assignable, will get error with: QMap
03/02/12 17 03/02/12 18