Skip to content

Commit d510e1e

Browse files
committed
Add swapItemsAt() to QVector
This closes one compatibility gap with QList, to make it easier to replace QList with QVector in Qt6. Change-Id: I5655bc4cd2150a6f09a1ed68c0742f3b42ca47e4 Reviewed-by: Simon Hausmann <simon.hausmann@qt.io>
1 parent 587bdd1 commit d510e1e

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

src/corelib/tools/qvector.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,13 @@ class QVector
251251
T value(int i) const;
252252
T value(int i, const T &defaultValue) const;
253253

254+
void swapItemsAt(int i, int j) {
255+
Q_ASSERT_X(i >= 0 && i < size() && j >= 0 && j < size(),
256+
"QVector<T>::swap", "index out of range");
257+
detach();
258+
qSwap(d->begin()[i], d->begin()[j]);
259+
}
260+
254261
// STL compatibility
255262
typedef T value_type;
256263
typedef value_type* pointer;

src/corelib/tools/qvector.qdoc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,16 @@
288288
never fails.
289289
*/
290290

291+
/*! \fn template <typename T> void QVector<T>::swapItemsAt(int i, int j)
292+
\since 5.14
293+
294+
Exchange the item at index position \a i with the item at index
295+
position \a j. This function assumes that both \a i and \a j are
296+
at least 0 but less than size(). To avoid failure, test that both
297+
\a i and \a j are at least 0 and less than size().
298+
*/
299+
300+
291301
/*! \fn template <typename T> bool QVector<T>::operator==(const QVector<T> &other) const
292302

293303
Returns \c true if \a other is equal to this vector; otherwise

tests/auto/corelib/tools/qvector/tst_qvector.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,8 @@ private slots:
331331

332332
void insertMove() const;
333333

334+
void swapItemsAt() const;
335+
334336
private:
335337
template<typename T> void copyConstructor() const;
336338
template<typename T> void add() const;
@@ -2990,5 +2992,22 @@ void tst_QVector::insertMove() const
29902992
QCOMPARE(Movable::counter.loadAcquire(), instancesCount);
29912993
}
29922994

2995+
void tst_QVector::swapItemsAt() const
2996+
{
2997+
QVector<int> v;
2998+
v << 0 << 1 << 2 << 3;
2999+
3000+
v.swapItemsAt(0, 2);
3001+
QCOMPARE(v.at(0), 2);
3002+
QCOMPARE(v.at(2), 0);
3003+
3004+
auto copy = v;
3005+
copy.swapItemsAt(0, 2);
3006+
QCOMPARE(v.at(0), 2);
3007+
QCOMPARE(v.at(2), 0);
3008+
QCOMPARE(copy.at(0), 0);
3009+
QCOMPARE(copy.at(2), 2);
3010+
}
3011+
29933012
QTEST_MAIN(tst_QVector)
29943013
#include "tst_qvector.moc"

0 commit comments

Comments
 (0)