?? matrix.h
字號:
//----------------------------------------------------------------------
/*
文件名: matrix.h
目標: 用繼承vector<vector<T> >來建立矩陣類
*/
#ifndef _MATRIX_H_
#define _MATRIX_H_
//----------------------------------------------------------------------
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
//----------------------------------------------------------------------
template<class T>
class matrix: public vector<vector<T> >
{
public:
// 構造器1:空矩陣
matrix() {}
// 構造器2:設置行數和列數
matrix(size_t n,size_t m);
// 構造器3:設置行數、列數和初值
matrix(size_t n,size_t m,const T& tt);
// 返回矩陣行數
size_t numRows() { return size(); }
// 返回矩陣列數
size_t numCols() { return(*this)[0].size(); }
// 設置矩陣維數
void setDimensions(size_t r,size_t c);
// 安全檢查
void sanity_check();
// 矩陣輸出函數(未使用輸出運算符重載)
void printMat();
};
//----------------------------------------------------------------------
// 實現
template<class T>
matrix<T>::matrix(size_t n, size_t m): vector<vector<T> >(n)
{
for(size_t i=0; i<n; i++)
(*this)[i].resize(m);
}
template<class T>
matrix<T>::matrix(size_t n, size_t m, const T& tt): vector<vector<T> >(n)
{
for(size_t i=0; i<n; i++) {
vector<T>& ri = (*this)[i];
ri.resize(m);
fill(ri.begin(), ri.end(), tt);
}
}
template<class T>
void matrix<T>::setDimensions(size_t r, size_t c)
{
reserve(r);
resize(r);
for(size_t i=0; i<r; i++)
(*this)[i].resize(c);
}
template<class T>
void matrix<T>::sanity_check()
{
size_t r = numRows();
size_t c = numCols();
assert(capacity() == r);
for(size_t i=0; i<r; i++)
assert((*this)[i].size() == c && (*this)[i].capacity() == c);
}
template<class T>
void matrix<T>::printMat()
{
vector<T>::iterator it;
for(size_t i=0; i<numRows(); i++) {
vector<T>& ri = (*this)[i];
for(it=ri.begin(); it!=ri.end(); it++)
cout << setw(5) << *it;
cout << endl;
}
cout << endl;
}
//----------------------------------------------------------------------
#endif
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -