【C++】数组与矩阵


近两天看《数据结构》,总结一下数组与矩阵这部分的内容

一、数组

一个数组的每一个实例都是形如(索引,值)的数对集合,其中任意两个数对的索引都不相同。有关数组的操作如下:

  • 取值——对一个给定的索引,取对应数对中的值;
  • 存值——把一个新数对加到数对集合中。如果已存在一个索引相同的数对,就用新数对覆盖。

简而言之,就是索引和值构成的数对的集合就是数组。

二、矩阵

一个m*n的矩阵是一个m行、n列的表,m和n是矩阵的维数。矩阵在程序中一般是用一维数组就行映射,主要有行主映射(按行的顺序对元素一一映射)和列主映射(按列的顺序对元素一一映射)。博主使用的是行主映射,映射关系为:
map(i,j) = i * columns + j
其中columns表示数组的列数。

2.1 普通矩阵

对于普通矩阵采用行主映射方式,重载操作符()、=、+、-、<<,定义转置运算等操作

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 T&);
	matrix<T> operator *(const matrix<T>&) const;

	// 转置运算
	matrix<T> trans();


private:
	int theRows;  // 矩阵的行数
	int theColumns;  // 矩阵的列数
	T* element;  // 数组element
};

具体函数实现见文件arrayAndMatrix.h

2.2 特殊矩阵

对角矩阵(diagonalMatrix.h):只有对角元素非0,因此采用对角线映射,就是把所有对角线的元素从上到下一一映射到一维数组中;
三对角矩阵():只有对角线和对角线上下两条相邻的对角线,一共三条对角线上的元素是非0的,因此从下往上采用对角线映射即可;
下三角矩阵(

发布了96 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Thera_qing/article/details/103284231