jack06215

[tutorial] functional zip()

Jul 11th, 2020 (edited)
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. #include <iomanip>
  5. #include <functional>
  6. #include <iterator>
  7.  
  8. template<typename Collection, typename unop>
  9. void for_each(Collection col, unop op) {
  10.     std::for_each(col.begin(), col.end(), op);
  11. }
  12.  
  13. template<typename Collection, typename binop>
  14. Collection zip(Collection fc, Collection src, binop op) {
  15.     std::transform(fc.begin(), fc.end(), src.begin(), fc.begin(), op);
  16.     return fc;
  17. }
  18.  
  19. int main()
  20. {
  21.     auto println = [](const char *message) { std::cout << "\n" << message << '\n'; };
  22.     auto lambda_echo = [](int i) { std::cout << std::setw(3) << i; };
  23.     std::vector<int> col{ 23, 23, 37, 42, 23, 23, 37 };
  24.     std::vector<int> another_col = {40, 22, 22, 24, 23, 45, 34};
  25.  
  26.     // collections addition
  27.     auto zip_col = zip(col, another_col, std::plus<int>());
  28.     println("running zip<T> operation");
  29.     for_each(zip_col, lambda_echo);
  30.  
  31.     return 0;
  32. }
Add Comment
Please, Sign In to add comment