C ++ implements a two-dimensional array class

Source: Internet
Author: User
#ifndef __H_MATRIX_H__#define __H_MATRIX_H__#include <vector>using namespace std;template<typename Object>class matrix{public:matrix(int rows, int cols):array(rows){for (int i=0; i<rows; i++)array[i].resize(cols);}const vector<Object> & operator[](int row)const{return array[row];}vector<Object>& operator[](int row){return array[row];}int numrows()const{return array.size();}int numcols()const{return numrows() ? array[0].size() : 0;}private:vector< vector<Object> > array;};#endif//__H_MATRIX_H__

Test. cpp

#include "matrix.h"#include <iostream>using namespace std;int main(){matrix<int> matrixArray(3,5);int i,j;for (i=0; i<matrixArray.numrows(); i++){for(j=0; j<matrixArray.numcols(); j++)matrixArray[i][j] = i+j;}for (i=0; i<matrixArray.numrows(); i++){for(j=0; j<matrixArray.numcols(); j++)cout<< matrixArray[i][j]<<ends;cout<<endl;}return 0;}

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.