Use vector to write a matrix template

Source: Internet
Author: User

Vectors can write matrices over two dimensions. I was thinking about this problem when I was reading vector and string. How it should be written. Using a similar idea to a two-dimensional array, if the vector holds a vector that is not available, and the access operation is much more convenient than the array. The procedure is as follows:

#include <iostream>
#include <vector>
using namespace std;
Template<typename t>//Template
class Matrix {public
:
	matrix (int rows, int cols): arr (rows)
	{/
		* for (rsize_t t = 0;t < rows;t++)
			arr[t].resize (cols); */For
		(auto &thisrow:arr)//auto automatically inferred
			. Resize (cols);
	}
	Matrix (vector<vector<t>> V): arr{v}	//Copy copy constructor
	{}
	matrix (vector<vector<t> > &&v): arr{std::move (v)}//Mobile copy constructor
	{}
	const vector<t> &operator[] (int row) const// Overloaded subscript reference
	{return
		arr[row];
	}
	vector<t>& operator[] (int row)
	{return
		arr[row];
	}				
	int numrows () const//number of rows
	{return
		arr.size ();
	}
	int numcols () const	//Number of columns
	{return
		numrows () arr[0].size (): 0;
	}
Private:
	vector<vector<t>>arr;
};
This is achieved.

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.