Last active
December 18, 2015 19:49
-
-
Save borisbat/5836110 to your computer and use it in GitHub Desktop.
C++11 STL
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 <iostream> | |
#include <vector> | |
#include <functional> | |
#include <initializer_list> | |
#include <string> | |
using namespace std; | |
template <typename TT> | |
class RArray : protected vector<TT> | |
{ | |
public: | |
RArray() {} | |
RArray( const initializer_list<TT> & val ) : vector<TT>(val) {} | |
void push ( const TT & value ) { | |
vector<TT>::push_back(value); | |
} | |
void each ( const function<void (const TT &)> & fn ) const { | |
for ( const auto & v : *this ) | |
fn ( v ); | |
} | |
template <typename TR> | |
RArray<TR> map ( const function<TR (const TT & )> &fn ) const { | |
RArray<TR> res; | |
for ( const auto & v : *this ) | |
res.push( fn(v) ); | |
return res; | |
} | |
template <typename TR> | |
TR fold ( const TR & zero, const function<TR (const TR &, const TT &)> & fn ) const { | |
TR res = zero; | |
for ( const auto & v : *this ) | |
res = fn(res, v); | |
return res; | |
} | |
}; | |
template <typename FU, typename T> | |
void each(const FU & fn, const T& value) | |
{ | |
value.each(fn); | |
} | |
template <typename FU, typename U, typename... T> | |
void each(const FU & fn, const U& head, const T&... tail) | |
{ | |
head.each(fn); | |
each(fn, tail...); | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
RArray<int> foo = {1, 2, 3}; | |
foo.each([&](int t){ | |
cout << t << " "; | |
}); | |
cout << endl; | |
auto bar = foo.map<int>([&](int t) { | |
return t + 3; | |
}); | |
auto res = bar.fold<string>( "", [&](const string & s, int t){ | |
return s + to_string(t) + " "; | |
}); | |
cout << res << endl; | |
each ( [&](int t){ | |
cout << t << " "; | |
}, foo, bar ); | |
cout << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment