SmallVector: Allow initialization and assignment from initializer_list.

Modeled after std::vector.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@231015 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Benjamin Kramer 2015-03-02 21:16:04 +00:00
parent f027454edc
commit 3ad0e2cd45
2 changed files with 41 additions and 0 deletions

View File

@ -24,6 +24,7 @@
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <iterator>
#include <memory>
@ -432,6 +433,10 @@ public:
this->setEnd(this->end() + NumInputs);
}
void append(std::initializer_list<T> IL) {
append(IL.begin(), IL.end());
}
void assign(size_type NumElts, const T &Elt) {
clear();
if (this->capacity() < NumElts)
@ -440,6 +445,11 @@ public:
std::uninitialized_fill(this->begin(), this->end(), Elt);
}
void assign(std::initializer_list<T> IL) {
clear();
append(IL);
}
iterator erase(iterator I) {
assert(I >= this->begin() && "Iterator to erase is out of bounds.");
assert(I < this->end() && "Erasing at past-the-end iterator.");
@ -633,6 +643,10 @@ public:
return I;
}
void insert(iterator I, std::initializer_list<T> IL) {
insert(I, IL.begin(), IL.end());
}
template <typename... ArgTypes> void emplace_back(ArgTypes &&... Args) {
if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
this->grow();
@ -865,6 +879,10 @@ public:
this->append(R.begin(), R.end());
}
SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
this->assign(IL);
}
SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
if (!RHS.empty())
SmallVectorImpl<T>::operator=(RHS);
@ -895,6 +913,10 @@ public:
return *this;
}
const SmallVector &operator=(std::initializer_list<T> IL) {
this->assign(IL);
return *this;
}
};
template<typename T, unsigned N>

View File

@ -11,6 +11,7 @@
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "gtest/gtest.h"
@ -906,4 +907,22 @@ TEST(SmallVectorTest, EmplaceBack) {
}
}
TEST(SmallVectorTest, InitializerList) {
SmallVector<int, 2> V1 = {};
EXPECT_TRUE(V1.empty());
V1 = {0, 0};
EXPECT_TRUE(makeArrayRef(V1).equals({0, 0}));
V1 = {-1, -1};
EXPECT_TRUE(makeArrayRef(V1).equals({-1, -1}));
SmallVector<int, 2> V2 = {1, 2, 3, 4};
EXPECT_TRUE(makeArrayRef(V2).equals({1, 2, 3, 4}));
V2.assign({4});
EXPECT_TRUE(makeArrayRef(V2).equals({4}));
V2.append({3, 2});
EXPECT_TRUE(makeArrayRef(V2).equals({4, 3, 2}));
V2.insert(V2.begin() + 1, 5);
EXPECT_TRUE(makeArrayRef(V2).equals({4, 5, 3, 2}));
}
} // end namespace