不规则二维数组
不规则二维数组的创建和使用
#include<iostream>
using namespace std;
int main()
{
int numberOfRows = 5;
int length[5] = {6,3,4,2,7};
int **irregularArray = new int *[numberOfRows];
for(int i = 0;i<numberOfRows; i++)
{
irregularArray[i] = new int [length[i]];
}
irregularArray[2][3] = 5;
irregularArray[4][6] = irregularArray[2][3]+2;
irregularArray[1][1] = 3;
cout<<irregularArray[2][3]<<endl;
cout<<irregularArray[4][6]<<endl;
cout<<irregularArray[1][1]<<endl;
}
矩阵
定义和操作
一个m*n的矩阵是一个m行,n列的表,m和n是矩阵的维数。
常见的矩阵操作:
矩阵的转置;
矩阵的加法;
矩阵的乘法;
类matrix
下面展示一些 内联代码片
。
template<class T>
class Matrix
{
friend ostream& operator<<(ostream& ,const Matrix<T>& );
public:
Matrix(int theRows = 0,int theColumns = 0); //空构造函数
Matrix(const Matrix<T>& );//复制构造器
~Matrix(){delete [] element;}//析构器
int Rows() const{return theRows;}//返回行
int columns() const{return theColumns;}//返回列
T& operator()(int i,int j) const;//重载“()”运算符
Matrix<T>& operator=(const Matrix<T>&);//重载=运算符
Matrix<T> operator+() const;//重载+运算符
Matrix<T> operator+(const Matrix<T>&) const;//重载+运算符
Matrix<T> operator-() const;//重载-运算符
Matrix<T> operator-(const Matrix<T>& ) const;//重载-运算符
Matrix<T> operator*(const Matrix<T>& ) const;//重载*运算符
Matrix<T>& operator+=(const T& );//重载+=运算符
private:
int theRows;
int theColumns;
T* element;
};
操作
下面展示一些 内联代码片
。
template <class T>
Matrix<T>::Matrix(int theRows,int theColumns)
{
if(theRows < 0|| theColumns <0) cerr<<"Rows and columns must be >=0"<<endl;
if(theRows == 0|| theColumns == 0) cerr<<"Either both or rows and columns should be zero"<<endl;
this->theRows = theRows;
this->theColumns = theColumns;
element = new T [theRows*theColumns];
}
template<class T>
Matrix<T>::Matrix(const Matrix<T>& m)
{
theRows = m.theRows;
theColumns = m.theColumns;
element = new T[theRows*theColumns];
copy(m.element,m.element+theRows*theColumns,element);
return *this;
}
tempalte <class T>
T& Matrix<T>::operator()(int ,int j) const
{
if (i < 1||i>theRows||
j<1||j>theColumns )
cerr<<"wrong wrong wrong"<<endl;
return element[(i-1)*theColumns+j-1];
}
Matrix<T> Matrix<T>::operator(const Matrix<T>& m) const
{
Matrix<T> w (theRows,theColumns);
for(int i=0; i<theRows*theColumns;i++)
{
w.element[i] = element[i]+m.element[i];
}
return w;
}
tempalte<class T>
Matrix<T> Matrix<T>::operator*(const Matrix<T>& m)
{
Matrix<T> w(theRows,m.theColumns);
int ct = 0,cm = 0,cw = 0;
for(int i = 1;i<theRows;i++)
{
for(int j = 1;j<=m.theColumns;j++)
{
T sum = element[ct]*m.element[cm];
for(int k = 2;k<=theColumns;k++)
{
ct++;
cm += m.theColumns;
sum += element[ct]*m.element[cm];
}
w.element[cw++] = sum;
ct -= theColumns -1;
cm = j;
}
ct+=theColumns;
cm = 0;
}
return w;
}
解析:
上面的代码中,有几点要说一下:
第一:在()运算符重载的时候,小括号中有两个值,int i和int j,这代表着该元素再数组中的位置处在第几行,第几列。经过函数后,返回的是一个element[i]的形式。这是因为element我们定义的时候就是把element定义成一个一维数组,也就是说,我们把二维数组所占据的二维空间拉成直线的一维空间进行储存。所以每一个二维数组中的元素再一维数组中都有一个对应的位置。(即一个映射函数)
第二,在重载矩阵乘法运算符的时候,我们采用三循环的办法,这种办法消耗的时间复杂度很大。其中cm += m.theColumns;这句代码所表现的和上面的一条的思想是一样的,也是二维数组转化成一维数组的一个过程。