fork download
  1. #include <array>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. #include <cassert>
  6. #include <cmath>
  7. #include <cstdint>
  8.  
  9. struct vertex
  10. {
  11. std::array<double, 3> vector_;
  12. std::uint32_t color_;
  13.  
  14. double & operator () (std::size_t index) { assert(index < 3); return vector_[index]; }
  15. double operator () (std::size_t index) const { assert(index < 3); return vector_[index]; }
  16.  
  17. double abs() const
  18. {
  19. return std::sqrt(
  20. vector_[0] * vector_[0] +
  21. vector_[1] * vector_[1] +
  22. vector_[2] * vector_[2]
  23. );
  24. }
  25.  
  26. // turns RGBA value to gray, alpha channel is ignored for this
  27. std::uint32_t gray() const
  28. {
  29. std::uint8_t g =
  30. ((color_ >> 24) +
  31. ((color_ >> 16) & 0xFF) +
  32. ((color_ >> 8) & 0xFF)) / 3;
  33. return ((g << 24) | (g << 16) | (g << 8) | (color_ & 0xFF));
  34. }
  35. };
  36.  
  37. class field
  38. {
  39. public:
  40. // the explicit prevents std::size_t's to be implicitely cast into fields ;-)
  41. explicit field(std::size_t size)
  42. : vertices_(size)
  43. {
  44. }
  45.  
  46. vertex & operator() (std::size_t index) { assert(index < vertices_.size()); return vertices_[index]; }
  47. vertex operator() (std::size_t index) const { assert(index < vertices_.size()); return vertices_[index]; }
  48.  
  49. private:
  50. // this is still pretty contigous
  51. std::vector<vertex> vertices_;
  52. };
  53.  
  54. int main()
  55. {
  56. field f(2);
  57. vertex & v = f(1);
  58. v(2) = 5;
  59.  
  60. // also: this is a copy of v, so changing v2 will not affect f[1][2]
  61. vertex v2 = v;
  62. v2(2) = 2;
  63.  
  64. std::cout << f(1)(2) << std::endl;
  65.  
  66. return 0;
  67. }
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
5