Use Vector to implement matrix.

Source: Internet
Author: User

 

As we all know, C ++ does not provide the default matrix type. But most of the time we can

Following the C usage, you can declare a two-dimensional array to declare the matrix. This article describes another method,

To implement a matrix class and express the concept of a two-dimensional array. The specific implementation is a two-dimensional vector.

 

 

# Ifndef matrix_h

# Define matrix_h

 

# Include <vector>

Using STD: vector;

 

Template <typename T>

Class Matrix

{

PRIVATE:

Vector <vector <t> vv;

Int row;

Int Col;

Public:

Matrix (INT rows, int Cols): VV (rows), row (rows), COL (Cols)

{

For (INT I = 0; I <row; ++ I) // The only note is how to construct a two-dimensional vector. First construct a vector <>,

// Initialize the length of the vector.

{

VV [I]. Resize (Cols );

}

}

 

Const vector <t> & operator [] (INT row) const

{

If (row> = This-> row)

{

Throw "Index out of range"; // here we can throw a defined exception or not, because the vector will also check whether the index is out of bounds.

}

Return VV [row];

}

 

Vector <t> & operator [] (INT row) // non-const version, used for writing. Generally, the compiler automatically selects the matching function for calling.

{

If (row> = This-> row)

{

Throw "Index out of range ";

}

Return VV [row];

}

 

Int getrownum () const {return row;} // gets the number of rows

Int getcolnum () const {return Col;} // gets the number of columns.

 

};

 

# Endif

 

 

Here we do not need to define the copy constructor and the value assignment constructor, because the default one is enough.

The above code has been compiled and tested by vs2008.

 

 

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.