diff options
author | Mathias Hasselmann <mathias.hasselmann@kdab.com> | 2013-07-04 13:27:15 +0200 |
---|---|---|
committer | The Qt Project <gerrit-noreply@qt-project.org> | 2013-09-08 16:13:16 +0200 |
commit | 50e2db6a752b5d8b3af3023ff4cebb13ef2b9a2a (patch) | |
tree | 7c20be51f02606d8c9e2269a3d37da1bea6d49cc /tests/auto/corelib/tools/qmap/tst_qmap.cpp | |
parent | 69e21f1a86c201b817611d0bb237999e809cde0f (diff) |
Add first/last accessors to QMap
QMap explicitly sorts its entries by key value. For an ordered container
it's (often?) useful to access the first or last entry, for instance to
quickly compute the next key of the mapping. The first entry is easily
accessible by the STL begin() method, but for accessing the last entry
pretty ugly iterator arithmetics must be applied: *(end() - 1). With
their first() and last() accessors the container classes QList and
QVector provide a much nicer method of accessing extrema, so for
consistency this syntactical sugar also should be applied to QMap.
Change-Id: Ibd544acbad8c3ac16f12a1e74362207ea1694375
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Reviewed-by: Thorbjørn Lund Martsum <tmartsum@gmail.com>
Diffstat (limited to 'tests/auto/corelib/tools/qmap/tst_qmap.cpp')
-rw-r--r-- | tests/auto/corelib/tools/qmap/tst_qmap.cpp | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/tests/auto/corelib/tools/qmap/tst_qmap.cpp b/tests/auto/corelib/tools/qmap/tst_qmap.cpp index de9fa41feb..dea657f842 100644 --- a/tests/auto/corelib/tools/qmap/tst_qmap.cpp +++ b/tests/auto/corelib/tools/qmap/tst_qmap.cpp @@ -59,6 +59,7 @@ private slots: void count(); void clear(); void beginEnd(); + void firstLast(); void key(); void swap(); @@ -377,6 +378,34 @@ void tst_QMap::beginEnd() QVERIFY( map.constBegin() != map2.constBegin() ); } +void tst_QMap::firstLast() +{ + // sample string->string map + StringMap map; + map.insert("0", "a"); + map.insert("1", "b"); + map.insert("5", "e"); + + QCOMPARE(map.firstKey(), QStringLiteral("0")); + QCOMPARE(map.lastKey(), QStringLiteral("5")); + QCOMPARE(map.first(), QStringLiteral("a")); + QCOMPARE(map.last(), QStringLiteral("e")); + + // const map + const StringMap const_map = map; + QCOMPARE(map.firstKey(), const_map.firstKey()); + QCOMPARE(map.lastKey(), const_map.lastKey()); + QCOMPARE(map.first(), const_map.first()); + QCOMPARE(map.last(), const_map.last()); + + map.take(map.firstKey()); + QCOMPARE(map.firstKey(), QStringLiteral("1")); + QCOMPARE(map.lastKey(), QStringLiteral("5")); + + map.take(map.lastKey()); + QCOMPARE(map.lastKey(), map.lastKey()); +} + void tst_QMap::key() { { |