Skip to content

Commit

Permalink
COMMON: Add remove() to algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
hax0kartik authored and sev- committed Jun 1, 2023
1 parent 24c4d91 commit 698bb26
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
19 changes: 19 additions & 0 deletions common/algorithm.h
Expand Up @@ -390,6 +390,25 @@ void replace(It begin, It end, const Dat &original, const Dat &replaced) {
}
}

/**
* Removes all elements that are equal to value from the range [first, last).
* This function is the equivalent of std::remove.
*/
template<class It, class T>
It remove(It first, It last, const T& val) {
first = find(first, last, val);
if (first != last) {
It i = first;
while (++i != last) {
if (!(*i == val)) {
*first = move(*i);
first++;
}
}
}
return first;
}

/** @} */

} // End of namespace Common
Expand Down
10 changes: 10 additions & 0 deletions test/common/algorithm.h
Expand Up @@ -4,6 +4,7 @@
#include "common/func.h"
#include "common/algorithm.h"
#include "common/list.h"
#include "common/array.h"
#include "common/str.h"

class AlgorithmTestSuite : public CxxTest::TestSuite {
Expand Down Expand Up @@ -154,4 +155,13 @@ class AlgorithmTestSuite : public CxxTest::TestSuite {

TS_ASSERT_EQUALS(checkEqual(original.begin(), original.end(), expected.begin()), true);
}

void test_container_remove() {
Common::Array<int> original {1, 2, 3, 10, 4, 5};
Common::Array<int> expected {1, 2, 3, 4, 5};

Common::remove(original.begin(), original.end(), 10);

TS_ASSERT_EQUALS(checkEqual(expected.begin(), expected.end(), original.begin()), true);
}
};

0 comments on commit 698bb26

Please sign in to comment.