c++ - What type have multidimensional array? -


i writing own 2d matrix class. want design use of class close real math notation. example want access element matrix[3, 6]. c++ didn`t give ability, access base multidimensional array in next way:

int matrix[2][2] = {}; int val = matrix[1][0]; 

so decided make function return base array. role best function operator(). can access in next way: matrix()[1][0]. ok, started implement , stuck :(. have:

template <typename valtype> class matrix2d { protected:     valtype m_data[2][2] = {};  public:     valtype** operator()()  // <--- type?     {         return m_data;     } } 

but received compiler error in function above

error c2440: 'return' : cannot convert 'double [2][2]' 'double **'

i understand error no have idea must change avoid error? type function must return?

since tagged c++11, should use std::array. , use indexing operator, not call operator:

template <typename valtype> class matrix2d { protected:     using row = std::array<valtype, 2>;     std::array<row, 2> m_data;  public:     row& operator[](size_t idx)     {         return m_data[idx];     } }; 

this way can write matrix[1][0] instead of having write matrix()[1][0] (which, frankly, looks typo).

additionally, if prefer both indices simultaneously, write call operator take both:

valuetype& operator()(size_t x, size_t y) {     return m_data[x][y]; } 

that allow matrix(1, 0) alternative matrix[1][0].


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -