fork(93) download
  1. #include <vector>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. template<class T>
  6. class Array2D {
  7. vector<T> data;
  8. size_t cols;
  9. public:
  10. template <class U>
  11. class Array2DIndexer {
  12. size_t offset;
  13. vector<U> &data;
  14. public:
  15. Array2DIndexer(size_t o, vector<U> &dt) : offset(o), data(dt) {}
  16. T& operator[](size_t index) {
  17. return data[offset+index];
  18. }
  19. };
  20. Array2D(size_t r, size_t c) : data (r*c), cols(c) {}
  21. Array2DIndexer<T> operator[](size_t index) {
  22. return Array2DIndexer<T>(index*cols, data);
  23. }
  24. };
  25.  
  26. int main() {
  27. Array2D<int> a2d(10, 20);
  28. for (int r = 0 ; r != 10 ; r++) {
  29. for (int c = 0 ; c != 20 ; c++) {
  30. a2d[r][c] = r+2*c+1;
  31. }
  32. }
  33. for (int r = 0 ; r != 10 ; r++) {
  34. for (int c = 0 ; c != 20 ; c++) {
  35. cout << a2d[r][c] << " ";
  36. }
  37. cout << endl;
  38. }
  39. return 0;
  40. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 
4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 
5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 
6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 
7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 
8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 
9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 
10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48