stl-compat.cc 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // -*- mode: c++; coding: utf-8 -*-
  2. /// @file stl-compat.cc
  3. /// @brief Using ra:: array & iterator types with the STL algos & types.
  4. // (c) Daniel Llorens - 2014
  5. // This library is free software; you can redistribute it and/or modify it under
  6. // the terms of the GNU Lesser General Public License as published by the Free
  7. // Software Foundation; either version 3 of the License, or (at your option) any
  8. // later version.
  9. // ra:: iterators are only partially STL compatible, because of copiability,
  10. // lack of random access (which for the STL also means linear, but at least for
  11. // 1D expressions it should be available), etc. Check some cases here.
  12. #include <iostream>
  13. #include <iterator>
  14. #include "ra/complex.hh"
  15. #include "ra/test.hh"
  16. #include "ra/ra.hh"
  17. using std::cout, std::endl, std::flush, ra::TestRecorder;
  18. int main()
  19. {
  20. TestRecorder tr;
  21. tr.section("random access iterators");
  22. {
  23. // TODO rank-0 begin()/end() in ra::Small
  24. // TODO others?
  25. }
  26. tr.section("copyable iterators, but not random access");
  27. {
  28. {
  29. ra::Big<int, 1> a = { 1, 2, 3 };
  30. ra::Big<int, 1> b = { 0, 0, 0 };
  31. std::transform(a.begin(), a.end(), b.begin(), [](int a) { return -a; });
  32. tr.test_eq(a, -b);
  33. }
  34. {
  35. ra::Big<int, 2> a({2, 3}, ra::_0 - 2*ra::_1);
  36. ra::Big<int, 2> b({2, 3}, 99);
  37. std::transform(a.begin(), a.end(), b.begin(), [](int a) { return -a; });
  38. tr.test_eq(a, -b);
  39. }
  40. {
  41. ra::Small<int, 2, 3> a(ra::_0 - 2*ra::_1);
  42. ra::Small<int, 2, 3> b(99);
  43. std::transform(a.begin(), a.end(), b.begin(), [](int a) { return -a; });
  44. tr.test_eq(a, -b);
  45. }
  46. }
  47. tr.section("raw, slippery pointers");
  48. {
  49. ra::Big<int, 1> a = {1, 2, 3};
  50. int b[] = { +1, -1, +1 };
  51. tr.test_eq(ra::Small<int, 3> {2, 1, 4}, a + ra::ptr(b));
  52. ra::ptr(b) = ra::Small<int, 3> {7, 4, 5};
  53. tr.test_eq(ra::Small<int, 3> {7, 4, 5}, ra::ptr(b));
  54. int cp[3] = {1, 2, 3};
  55. // ra::Big<int, 1> c({3}, &cp[0]); // forbidden, confusing for higher rank c (pointer matches as rank 1).
  56. ra::Big<int, 1> c({3}, ra::ptr(cp));
  57. tr.test_eq(ra::Small<int, 3> {1, 2, 3}, c);
  58. }
  59. tr.section("ptr with other iterators");
  60. {
  61. std::vector<int> a = {1, 2, 3};
  62. ra::Small<int, 3> b = ra::ptr(a.begin());
  63. tr.test_eq(ra::Small<int, 3> {1, 2, 3}, b);
  64. }
  65. tr.section("[ra12] check that begin() and end() match for empty views");
  66. {
  67. ra::Big<int, 3> aa({0, 2, 3}, 0.);
  68. auto a = aa(ra::all, 1);
  69. tr.info("begin ", a.begin().ii.c.p, " end ", a.end().ii.c.p).test(a.begin()==a.end());
  70. }
  71. return tr.summary();
  72. }