QVector - add functions takeFirst and takeLast

This patch adds takeFirst and takeLast which are functions
that QList also has.

Change-Id: I761f90b529774edc8fa96e07c6fcf76226123b20
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Thorbjørn Martsum 2013-02-16 20:20:35 +01:00 committed by The Qt Project
parent 510660080d
commit ab52e72292
3 changed files with 40 additions and 3 deletions

View File

@ -551,7 +551,7 @@
the vector can be empty, call isEmpty() before calling this
function.
\sa remove(), isEmpty()
\sa remove(), takeFirst(), isEmpty()
*/
/*! \fn void QVector::removeLast()
@ -561,9 +561,31 @@
empty. If the vector can be empty, call isEmpty() before calling
this function.
\sa remove(), removeFirst(), isEmpty()
\sa remove(), takeLast(), removeFirst(), isEmpty()
*/
/*! \fn T QVector::takeFirst()
Removes the first item in the vector and returns it. This function
assumes the vector is not empty. To avoid failure, call isEmpty()
before calling this function.
\sa takeLast(), removeFirst()
*/
/*! \fn T QVector::takeLast()
Removes the last item in the list and returns it. This function
assumes the vector is not empty. To avoid failure, call isEmpty()
before calling this function.
If you don't use the return value, removeLast() is more
efficient.
\sa takeFirst(), removeLast()
*/
/*! \fn QVector &QVector::fill(const T &value, int size = -1)
Assigns \a value to all items in the vector. If \a size is

View File

@ -140,6 +140,8 @@ public:
void remove(int i, int n);
inline void removeFirst() { Q_ASSERT(!isEmpty()); erase(d->begin()); }
inline void removeLast() { Q_ASSERT(!isEmpty()); erase(d->end() - 1); }
inline T takeFirst() { Q_ASSERT(!isEmpty()); T r = first(); removeFirst(); return r; }
inline T takeLast() { Q_ASSERT(!isEmpty()); T r = last(); removeLast(); return r; }
QVector<T> &fill(const T &t, int size = -1);

View File

@ -1410,11 +1410,12 @@ struct RemoveLastTestClass
void tst_QVector::removeFirstLast() const
{
// pop_pack - pop_front
QVector<int> t;
QVector<int> t, t2;
t.append(1);
t.append(2);
t.append(3);
t.append(4);
t2 = t;
t.pop_front();
QCOMPARE(t.size(), 3);
QCOMPARE(t.at(0), 2);
@ -1423,6 +1424,18 @@ void tst_QVector::removeFirstLast() const
QCOMPARE(t.at(0), 2);
QCOMPARE(t.at(1), 3);
// takefirst - takeLast
int n1 = t2.takeLast();
QCOMPARE(t2.size(), 3);
QCOMPARE(n1, 4);
QCOMPARE(t2.at(0), 1);
QCOMPARE(t2.at(2), 3);
n1 = t2.takeFirst();
QCOMPARE(t2.size(), 2);
QCOMPARE(n1, 1);
QCOMPARE(t2.at(0), 2);
QCOMPARE(t2.at(1), 3);
// remove first
QVector<int> x, y;
x.append(1);