Created
July 6, 2016 22:37
-
-
Save cjhanks/980936c92f6b844b1bfb1bf6db4eb9ad to your computer and use it in GitHub Desktop.
Example Remove IF
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
// vim: ts=2 sw=2 et | |
#include <cassert> | |
#include <algorithm> | |
#include <vector> | |
#include <iostream> | |
template <typename Container, typename Predicate> | |
void | |
RemoveIf(Container& container, Predicate predicate) | |
{ | |
auto head = std::begin(container); | |
auto tail = std::end(container); | |
auto good = head; | |
while (head != tail) { | |
if (predicate(*head)) { | |
std::iter_swap(good, head); | |
std::advance(good, 1); | |
} | |
std::advance(head, 1); | |
} | |
container.resize( | |
std::distance(std::begin(container), good)); | |
} | |
template <typename _Tp> | |
void | |
Print(_Tp data) | |
{ | |
for (const auto& elem: data) { | |
std::cerr << elem << "\n"; | |
} | |
} | |
int | |
main() | |
{ | |
// { | |
std::vector<int> D; | |
size_t i = 0; | |
std::generate_n(std::back_inserter(D), 26, [&](){return ++i;}); | |
// } | |
{ | |
auto test2 = D; | |
RemoveIf(test2, [](int d) { return d % 2 == 0; }); | |
assert(test2.size() == D.size() / 2); | |
} | |
{ | |
auto test3 = D; | |
RemoveIf(test3, [](int d) { return d % 3 == 0; }); | |
assert(test3.size() == D.size() / 3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment