From 50e2db6a752b5d8b3af3023ff4cebb13ef2b9a2a Mon Sep 17 00:00:00 2001 From: Mathias Hasselmann Date: Thu, 4 Jul 2013 13:27:15 +0200 Subject: Add first/last accessors to QMap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Reviewed-by: Thorbjørn Lund Martsum --- tests/auto/corelib/tools/qmap/tst_qmap.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'tests/auto/corelib/tools/qmap') 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() { { -- cgit v1.2.3