Need a unique gift idea?
A Pastebin account makes a great Christmas gift
SHARE
TWEET

Untitled

a guest Oct 12th, 2018 61 Never
Upgrade to PRO!
ENDING IN00days00hours00mins00secs
 
  1. // The recursive for starts with no arguments at all, and then runs a for
  2. // loop for every dimension, counting up
  3. template <std::size_t N, std::size_t I = 0, class F, class... Args>
  4. auto recursive_for(E&& expr, Args... args) {
  5.     if constexpr (I == N) {
  6.         for (std::size_t i = 0; i < std::get<0>(x).shape[I]; ++i)
  7.             expr(args..., i);
  8.     }
  9.     else {
  10.         for (std::size_t i = 0; i < std::get<0>(x).shape[I]; ++i)
  11.             recursive_for<N, I + 1>(x, args..., i);
  12.     }
  13. }
  14.  
  15. // So calling
  16. // recursive_for<1>(qview) will let you iterate over all elements in a
  17. // qview of dim == 2. But obviously that would not do anything (yet). To make it
  18. // perform some action we need to use a qfunction! Let's define a qfunction to print
  19. // qview's for us.
  20.  
  21. template <class T>
  22. void print(T& array) {
  23.     auto func = make_qfunction([](auto& el) { std::cout << el << ", " }, array);
  24.     recursive_for<1>(func); // hard coded 2D, can be generalized with tuple_size of the shape
  25. }
  26.  
  27. // now calling print(qview);
  28. // prints: 1, 2, 3, 4, 5, 6, 7, 8, 9,
  29.  
  30. // If we want to assign the result of a qfunction to a qview, we need
  31. // an assign function:
  32. template <class T, class E>
  33. auto assign_func(T& larr, E& rexpr)
  34. {
  35.     // note that the lhs argument is a reference!
  36.     return make_qfunction([](auto& lhs, auto rhs) { lhs = rhs; }, larr, rexpr);
  37. }
  38.  
  39. // And here we define the operator+ for qviews, returning a lazy qfunction
  40. template <class L, class R>
  41. auto operator+(L& larr, R& rarr) {
  42.     return qfunction([](const auto& lhs, const auto& rhs) {
  43.         return lhs + rhs;
  44.     }, larr, rarr);
  45. }
  46.  
  47. int main() {
  48.     std::vector<double> data = {1,2,3, 4,5,6, 7,8,9};
  49.     qview<std::vector<double>, 2> array(data, {3, 3});
  50.     qview<std::vector<double>, 2> result(std::vector<double>(9), {3, 3});
  51.     // assigns qfunction of array + array to result!
  52.     recursive_for<1>(assign_func(result, array + array));
  53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top