diff options
| author | Nathan James <n.james93@hotmail.co.uk> | 2020-11-03 14:57:08 +0000 |
|---|---|---|
| committer | Nathan James <n.james93@hotmail.co.uk> | 2020-11-03 14:57:10 +0000 |
| commit | 97e8da45f9459ce9334c2d387ada7d2cde9625f4 (patch) | |
| tree | e6ae888c2659f152f61b5dc50a52495e3ee9c65e | |
| parent | e8d67ef2dc93af671a2123caaf302709ba6e15d5 (diff) | |
[ADT] Add SmallVector::pop_back_n
Adds a method called pop_back_n to SmallVector.
This is more readable and less error prone than the alternatives of using
```lang=c++
Vector.resize(Vector.size() - N);
Vector.erase(Vector.end() - N, Vector.end());
for (unsigned I = 0;I<N;++I) Vector.pop_back();
```
Reviewed By: dblaikie
Differential Revision: https://reviews.llvm.org/D90576
| -rw-r--r-- | llvm/include/llvm/ADT/SmallVector.h | 6 | ||||
| -rw-r--r-- | llvm/unittests/ADT/SmallVectorTest.cpp | 3 |
2 files changed, 7 insertions, 2 deletions
diff --git a/llvm/include/llvm/ADT/SmallVector.h b/llvm/include/llvm/ADT/SmallVector.h index bb008af25f96..e042497473db 100644 --- a/llvm/include/llvm/ADT/SmallVector.h +++ b/llvm/include/llvm/ADT/SmallVector.h @@ -424,6 +424,12 @@ public: this->grow(N); } + void pop_back_n(size_type NumItems) { + assert(this->size() >= NumItems); + this->destroy_range(this->end() - NumItems, this->end()); + this->set_size(this->size() - NumItems); + } + LLVM_NODISCARD T pop_back_val() { T Result = ::std::move(this->back()); this->pop_back(); diff --git a/llvm/unittests/ADT/SmallVectorTest.cpp b/llvm/unittests/ADT/SmallVectorTest.cpp index dbe404869e2c..162716abe9ff 100644 --- a/llvm/unittests/ADT/SmallVectorTest.cpp +++ b/llvm/unittests/ADT/SmallVectorTest.cpp @@ -261,8 +261,7 @@ TYPED_TEST(SmallVectorTest, PushPopTest) { this->assertValuesInOrder(this->theVector, 2u, 2, 1); // Pop remaining elements - this->theVector.pop_back(); - this->theVector.pop_back(); + this->theVector.pop_back_n(2); this->assertEmpty(this->theVector); // Check number of constructor calls. Should be 2 for each list element, |
