[Original] multi-dimensional array subscript operator overload

Source: Internet
Author: User

If you encounter a pen question: design a matrix class, input the rows and columns through the constructor, and support the [] [] values and values.
This is actually a two-dimensional array subscript operator overload problem, the solution is as follows:
(1) Use a one-dimensional array instead of a two-dimensional array to allocate memory to obtain continuous memory space. When the value is calculated, the values of the corresponding rows and columns are obtained.
(2) design two classes: Reload operator [], one to get rows and one to get columns.
The implementation is as follows:

Code

Class matrixentry {
Friend class matrix; // you can access the private variable m_currentrow.
Public:
Matrixentry (int m, int N): m_row (M), m_col (N)
{
M_pmatrix = new int [M * n * sizeof (INT)];
}

~ Matrixentry ()
{
Delete m_pmatrix;
}

Int & operator [] (INT col)
{
Return m_pmatrix [m_currentrow * m_col + Col];
}

 

PRIVATE:
Int * m_pmatrix; // One-dimensional array of the storage matrix
Int m_row; // number of rows in the Matrix
Int m_col; // Number of columns in the Matrix
Int m_currentrow; // specifies the row to be accessed. The value is set by the matrix class below.
};

 

Class matrix {
Public:
Matrix (int m, int N): m_entry (m, n)
{
}

Matrixentry & operator [] (INT row)
{
M_entry.m_currentrow = row;
Return m_entry;
}

 

PRIVATE:
Matrixentry m_entry;
};

Test:

Test code

Int x = 1;
Int I;

Matrix M (5, 5 );

For (I = 0; I <5; I ++)
{
For (Int J = 0; j <5; j ++)
{
M [I] [J] = x ++;
}
}

For (I = 0; I <5; I ++)
{
For (Int J = 0; j <5; j ++)
{
Cout <m [I] [J] <Endl;
}
}

the above implementation only takes into account the most basic functions, and does not involve the error handling logic such as subscript out-of-bounds. If you are interested, you can complete it. If you want to design a generic class, replace int with T in template .

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.