组合容器(Associative Containers)

映射,字典或者集合是组合容器的例子。它们使用一个键来保存一个值。它们可以快速的查询它们的元素。我们将展示使用最多的组合容器QHash,同时也会展示一些C++11新的特性。

  1. QHash<QString, int> hash({{"b",2},{"c",3},{"a",1}});
  2. qDebug() << hash.keys(); // a,b,c - unordered
  3. qDebug() << hash.values(); // 1,2,3 - unordered but same as order as keys
  4. QVERIFY(hash["a"] == 1);
  5. QVERIFY(hash.value("a") == 1);
  6. QVERIFY(hash.contains("c") == true);
  7. { // JAVA iterator
  8. int sum =0;
  9. QHashIterator<QString, int> i(hash);
  10. while (i.hasNext()) {
  11. i.next();
  12. sum+= i.value();
  13. qDebug() << i.key() << " = " << i.value();
  14. }
  15. QVERIFY(sum == 6);
  16. }
  17. { // STL iterator
  18. int sum = 0;
  19. QHash<QString, int>::const_iterator i = hash.constBegin();
  20. while (i != hash.constEnd()) {
  21. sum += i.value();
  22. qDebug() << i.key() << " = " << i.value();
  23. i++;
  24. }
  25. QVERIFY(sum == 6);
  26. }
  27. hash.insert("d", 4);
  28. QVERIFY(hash.contains("d") == true);
  29. hash.remove("d");
  30. QVERIFY(hash.contains("d") == false);
  31. { // hash find not successfull
  32. QHash<QString, int>::const_iterator i = hash.find("e");
  33. QVERIFY(i == hash.end());
  34. }
  35. { // hash find successfull
  36. QHash<QString, int>::const_iterator i = hash.find("c");
  37. while (i != hash.end()) {
  38. qDebug() << i.value() << " = " << i.key();
  39. i++;
  40. }
  41. }
  42. // QMap
  43. QMap<QString, int> map({{"b",2},{"c",2},{"a",1}});
  44. qDebug() << map.keys(); // a,b,c - ordered ascending
  45. QVERIFY(map["a"] == 1);
  46. QVERIFY(map.value("a") == 1);
  47. QVERIFY(map.contains("c") == true);
  48. // JAVA and STL iterator work same as QHash