[ADT] Add drop_end.

This patch adds drop_end that is analogical to drop_begin.
It tries to fill the functional gap where one could drop first elements but not the last ones.
The need for it came in when refactoring clang-format.

Reviewed By: dblaikie

Differential Revision: https://reviews.llvm.org/D122009
This commit is contained in:
Marek Kurdej 2022-03-18 14:18:37 +01:00
parent e725e2afe0
commit df4da5f37d
2 changed files with 31 additions and 0 deletions

View File

@ -268,6 +268,13 @@ template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N = 1) {
adl_end(RangeOrContainer));
}
/// Return a range covering \p RangeOrContainer with the last N elements
/// excluded.
template <typename T> auto drop_end(T &&RangeOrContainer, size_t N = 1) {
return make_range(adl_begin(RangeOrContainer),
std::prev(adl_end(RangeOrContainer), N));
}
// mapped_iterator - This is a simple iterator adapter that causes a function to
// be applied whenever operator* is invoked on the iterator.

View File

@ -457,6 +457,30 @@ TEST(STLExtrasTest, DropBeginDefaultTest) {
EXPECT_EQ(i, 5);
}
TEST(STLExtrasTest, DropEndTest) {
SmallVector<int, 5> vec{0, 1, 2, 3, 4};
for (int n = 0; n < 5; ++n) {
int i = 0;
for (auto &v : drop_end(vec, n)) {
EXPECT_EQ(v, i);
i += 1;
}
EXPECT_EQ(i, 5 - n);
}
}
TEST(STLExtrasTest, DropEndDefaultTest) {
SmallVector<int, 5> vec{0, 1, 2, 3, 4};
int i = 0;
for (auto &v : drop_end(vec)) {
EXPECT_EQ(v, i);
i += 1;
}
EXPECT_EQ(i, 4);
}
TEST(STLExtrasTest, EarlyIncrementTest) {
std::list<int> L = {1, 2, 3, 4};