I have searched about mapping functions in n dimensional array but didn't find particular answer. I want to know that how multidimensional arrays works i c++? what is general formula for finding element at particular index in n dimensional array.?
            Asked
            
        
        
            Active
            
        
            Viewed 47 times
        
    -3
            
            
        - 
                    http://stackoverflow.com/a/3755221/14065 – Martin York Mar 04 '16 at 07:30
 - 
                    The duplicate doesn't answers the question as I interpret it - but it's vague. For whatever it's worth, given say `T a[4][5][6];`, the compiler typically creates the equivalent of `T _a[4 * 5 * 6]`, with any access to `a[i][j][k]` being analgous to `_a[k + j*6 + i*6*5]`. In other words, the elements are still contiguous, and varying the right-most index moves to the neighbouring element in memory. – Tony Delroy Mar 04 '16 at 07:34
 
2 Answers
1
            
            
        Given a k-dimension array arr[n,1][n,2][n,3]...[n,k], the index of an element at arr[x,1][x,2][x,3]...[x,k] is x,k + x,(k-1) * n,k + x,(k-2) * n,k * n,(k-1) + ... + x,1 * n,2 * n,3 * ... * n,k.
        Nard
        
- 1,006
 - 7
 - 8
 
-1
            
            
        Redefine operator[] that return object with redefined oprator[]
template<T>
struct Matrix {
  // initialization and access checking skipped
  typedef std::vector<T> t_raw;
  typedef std::vector<t_raw> t_col;
  t_col m_mat;
  struct Idx {
    Matrix* mat;
    size_t row;
    T& operator[](size_t col) {
      return this->mat->m_mat[ this->row ][col];
    };
  }
  Idx operator[](size_t row) {
    Idx idx;
    idx.mat = this;
    idx.row = row;
    return idx;
  };
  friend class Idx;
};
Matrix<int> m;
m[1][2] = 5;
        oklas
        
- 7,935
 - 2
 - 26
 - 42