Skip to content

Instantly share code, notes, and snippets.

@ueokande
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ueokande/1d2d4e5ef733f78949e7 to your computer and use it in GitHub Desktop.
Save ueokande/1d2d4e5ef733f78949e7 to your computer and use it in GitHub Desktop.
C++ /= block
#include <functional>
#include <vector>
#include <iostream>
template <typename T>
class Array {
public:
Array(const std::initializer_list<T> &data)
: each(*this), keep_if(*this), data(data)
{}
struct each_t {
each_t(Array<T> &parent) : parent(parent) {}
void operator /= (std::function<void(T)> f) {
for (auto x : parent.data) { f(x); }
}
void operator /= (std::function<void(T, int)> f) {
for (auto it = parent.data.begin(); it != parent.data.end(); ++it) {
f(*it, it - parent.data.begin());
}
}
Array<T> &parent;
} each;
struct keep_if_t {
keep_if_t(Array<T> &parent) : parent(parent) {}
void operator /= (std::function<bool(T)> f) {
for (auto it = parent.data.begin(); it != parent.data.end(); ++it) {
if (!f(*it)) {
it = parent.data.erase(it) - 1;
}
}
}
Array<T> &parent;
} keep_if;
private:
std::vector<T> data;
};
int main() {
Array<char> array {'a', 'b', 'c', 'd', 'e'};
array.each /= [](char x){
std::cout << x << std::endl;
};
array.keep_if /= [](char x) {
return x <= 'c';
};
array.each /= [](char x, int i){
std::cout << i << ":" << x << std::endl;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment