fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4.  
  5. struct Foo
  6. {
  7. std::vector<int> bars;
  8. std::vector<char> bazs;
  9. std::size_t size;
  10.  
  11. Foo(size_t size, int bar = 0, char baz = 0) :
  12. bars(size, bar), bazs(size, baz), size{size}
  13. {
  14. }
  15.  
  16. auto operator[](size_t n)
  17. {
  18. // if (n >= size) ...
  19. struct
  20. {
  21. int &bar;
  22. char &baz;
  23. } temp{ bars[n], bazs[n] };
  24. return temp;
  25. }
  26. };
  27.  
  28.  
  29. int main()
  30. {
  31. Foo arr(30, 100, 'a'); // 30 items
  32.  
  33. std::cout << arr[29].bar << std::endl;
  34. std::cout << arr[29].baz << std::endl;
  35.  
  36. std::cout << arr.bars[29] << std::endl;
  37. std::cout << arr.bazs[29] << std::endl;
  38.  
  39. std::unique_ptr<Foo> arr2 = std::make_unique<Foo>(25, 10, 'b'); // 25 items
  40.  
  41. std::cout << arr2->operator[](15).bar << std::endl;
  42. std::cout << arr2->operator[](15).baz << std::endl;
  43.  
  44. arr2->bars[15] = 11;
  45. std::cout << arr2->bars[15] << std::endl;
  46. arr2->bazs[15] = 'c';
  47. std::cout << arr2->bazs[15] << std::endl;
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0s 4412KB
stdin
Standard input is empty
stdout
100
a
100
a
10
b
11
c