fork(2) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <numeric>
  5. #include <functional>
  6. #include <iterator>
  7. using namespace std;
  8. using namespace std::placeholders;
  9.  
  10. class sequence {
  11.  
  12. vector<int> data;
  13.  
  14. public:
  15. typedef vector<int>::const_iterator it;
  16.  
  17. // add
  18. sequence& operator<<(int rhs) {
  19. data.push_back(rhs);
  20. return *this;
  21. }
  22.  
  23. // reduce
  24. sequence& operator<<(function<int(int,int)> binary_op) {
  25. if (data.size() > 1) {
  26. const int result = accumulate (data.begin()+1, data.end(), *data.begin(), binary_op);
  27. data.clear();
  28. data.push_back (result);
  29. }
  30. return *this;
  31. }
  32.  
  33. // map
  34. sequence& operator<<(function<int(int)> unary_op) {
  35. transform(data.begin(), data.end(), data.begin(), unary_op);
  36. return *this;
  37. }
  38.  
  39. // manipulate
  40. sequence& operator<<(function<void(vector<int>::const_iterator begin, vector<int>::const_iterator end)> manip) {
  41. manip (data.begin(), data.end());
  42. return *this;
  43. }
  44. };
  45.  
  46. // functional objects
  47. auto sum = plus<int>();
  48. auto prod = multiplies<int>();
  49.  
  50. // template functor
  51. struct out {
  52. ostream& os_;
  53. out (ostream& os) : os_(os) {}
  54.  
  55. template <typename Iterator>
  56. void operator ()(Iterator begin, Iterator end) {
  57. copy (begin, end, ostream_iterator<typename Iterator::value_type>(os_," "));
  58. os_ << endl;
  59. }
  60. };
  61.  
  62. auto out_cout=out(cout);
  63.  
  64. // lambda
  65. auto change_sign = [](int x)->int { return -x; };
  66.  
  67. // function
  68. int sqr (int x) { return x*x; }
  69.  
  70. int main() {
  71. sequence seq;
  72. seq << 1 << 2 << 3 << out_cout
  73. << sum << out_cout
  74. << 4 << 5 << prod << out_cout
  75. << 2 << sqr << out_cout
  76. << -42 << change_sign << out_cout;
  77. }
  78.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
1 2 3 
6 
120 
14400 4 
-14400 -4 42