Last active
August 29, 2015 14:00
-
-
Save zachelko/11309613 to your computer and use it in GitHub Desktop.
Variation on std::remove_if which respects a bound for the number of values to remove
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cassert> | |
#include <functional> | |
#include <iostream> | |
#include <list> | |
#include <string> | |
#include <vector> | |
template <typename T, typename BinaryPredicate> | |
void bounded_remove_if(T &values, | |
BinaryPredicate predicate, | |
const typename T::value_type &exemplar, | |
const int bound) | |
{ | |
auto iterator = values.begin(); | |
int removed = 0; | |
while (iterator != values.end() && removed < bound) { | |
if (predicate(*iterator, exemplar)) { | |
++removed; | |
iterator = values.erase(iterator); | |
} else { | |
++iterator; | |
} | |
} | |
} | |
int main() | |
{ | |
// Remove at most one 3 | |
std::vector<int> intValues = { 0, 1, 2, 3, 3 }; | |
bounded_remove_if(intValues, std::equal_to<int>(), 3, 1); | |
assert(intValues.size() == 4); | |
// Remove at most one "d" | |
std::vector<std::string> stringValues = | |
{ std::string("a"), std::string("b"), std::string("c"), | |
std::string("d"), std::string("d") }; | |
bounded_remove_if(stringValues, std::equal_to<std::string>(), std::string("d"), 1); | |
assert(stringValues.size() == 4); | |
// Remove at most two 3s | |
std::list<int> listValues = { 0, 1, 2, 3, 3 }; | |
bounded_remove_if(listValues, std::equal_to<int>(), 3, 2); | |
assert(listValues.size() == 3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment