diff options
-rw-r--r-- | src/corelib/tools/qvector.h | 7 | ||||
-rw-r--r-- | src/corelib/tools/qvector.qdoc | 10 | ||||
-rw-r--r-- | tests/auto/corelib/tools/qvector/tst_qvector.cpp | 19 |
3 files changed, 36 insertions, 0 deletions
diff --git a/src/corelib/tools/qvector.h b/src/corelib/tools/qvector.h index 4e148c9c55..b763d6e7e2 100644 --- a/src/corelib/tools/qvector.h +++ b/src/corelib/tools/qvector.h @@ -251,6 +251,13 @@ public: T value(int i) const; T value(int i, const T &defaultValue) const; + void swapItemsAt(int i, int j) { + Q_ASSERT_X(i >= 0 && i < size() && j >= 0 && j < size(), + "QVector<T>::swap", "index out of range"); + detach(); + qSwap(d->begin()[i], d->begin()[j]); + } + // STL compatibility typedef T value_type; typedef value_type* pointer; diff --git a/src/corelib/tools/qvector.qdoc b/src/corelib/tools/qvector.qdoc index cb47d36356..c1b5054f93 100644 --- a/src/corelib/tools/qvector.qdoc +++ b/src/corelib/tools/qvector.qdoc @@ -288,6 +288,16 @@ never fails. */ +/*! \fn template <typename T> void QVector<T>::swapItemsAt(int i, int j) + \since 5.14 + + Exchange the item at index position \a i with the item at index + position \a j. This function assumes that both \a i and \a j are + at least 0 but less than size(). To avoid failure, test that both + \a i and \a j are at least 0 and less than size(). +*/ + + /*! \fn template <typename T> bool QVector<T>::operator==(const QVector<T> &other) const Returns \c true if \a other is equal to this vector; otherwise diff --git a/tests/auto/corelib/tools/qvector/tst_qvector.cpp b/tests/auto/corelib/tools/qvector/tst_qvector.cpp index f81ce11510..11c255b184 100644 --- a/tests/auto/corelib/tools/qvector/tst_qvector.cpp +++ b/tests/auto/corelib/tools/qvector/tst_qvector.cpp @@ -331,6 +331,8 @@ private slots: void insertMove() const; + void swapItemsAt() const; + private: template<typename T> void copyConstructor() const; template<typename T> void add() const; @@ -2990,5 +2992,22 @@ void tst_QVector::insertMove() const QCOMPARE(Movable::counter.loadAcquire(), instancesCount); } +void tst_QVector::swapItemsAt() const +{ + QVector<int> v; + v << 0 << 1 << 2 << 3; + + v.swapItemsAt(0, 2); + QCOMPARE(v.at(0), 2); + QCOMPARE(v.at(2), 0); + + auto copy = v; + copy.swapItemsAt(0, 2); + QCOMPARE(v.at(0), 2); + QCOMPARE(v.at(2), 0); + QCOMPARE(copy.at(0), 0); + QCOMPARE(copy.at(2), 2); +} + QTEST_MAIN(tst_QVector) #include "tst_qvector.moc" |