Skip to content

Commit 2d3b1a3

Browse files
committed
Add ke::EraseIf for pre-C++20 code.
1 parent e38cfe3 commit 2d3b1a3

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

Diff for: amtl/am-vector.h

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// vim: set sts=8 ts=2 sw=2 tw=99 et:
1+
// vim: set sts=8 ts=4 sw=4 tw=99 et:
22
//
33
// Copyright (C) 2013, David Anderson and AlliedModders LLC
44
// All rights reserved.
@@ -31,6 +31,7 @@
3131

3232
#include <stddef.h>
3333

34+
#include <algorithm>
3435
#include <vector>
3536

3637
namespace ke {
@@ -73,4 +74,10 @@ static inline void EmplaceAt(std::vector<T>* vec, size_t at, Args&&... item) {
7374
vec->emplace(vec->begin() + at, std::forward<Args>(item)...);
7475
}
7576

77+
template <typename T, typename A, typename Pred>
78+
static inline void EraseIf(std::vector<T, A>* vec, Pred pred) {
79+
auto it = std::remove_if(vec->begin(), vec->end(), pred);
80+
vec->erase(it, vec->end());
81+
}
82+
7683
} // namespace ke

Diff for: tests/test-vector.cpp

+11
Original file line numberDiff line numberDiff line change
@@ -304,3 +304,14 @@ TEST(Vector, Remove) {
304304
EXPECT_EQ(thing1->refcount, (size_t)1);
305305
EXPECT_EQ(thing2->refcount, (size_t)1);
306306
}
307+
308+
TEST(Vector, EraseIf) {
309+
std::vector<int> items = {1, 2, 3, 4, 5};
310+
ke::EraseIf(&items, [](int item) -> bool {
311+
return item % 2 == 0;
312+
});
313+
EXPECT_EQ(items.size(), (size_t)3);
314+
EXPECT_EQ(items[0], 1);
315+
EXPECT_EQ(items[1], 3);
316+
EXPECT_EQ(items[2], 5);
317+
}

0 commit comments

Comments
 (0)