matrix.h
#pragma once
#ifndef __MATRIX_BASE__
#define __MATRIX_BASE__
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
public:
Matrix() {};
Matrix(int row, int col);
Matrix(const Matrix &A);
~Matrix() {};
void print(int row);
void init(){
array.resize(_row);
array[0].resize(_col);
}
//运算符重载
Matrix& operator + (const Matrix& rhs);
Matrix& operator = (const Matrix& rhs);
void add_row_element(int nrow, vector<double> vec);
private:
int _row;
int _col;
vector<vector<double>> array;
};
#endif // !__MATRIX_BASE__
matrix.cpp
Matrix::Matrix(int row, int col)
{
if (row < 0 || col < 0){
cout << "Row or col must be positive." << endl;
Matrix();
}
else {
_row = row;
_col = col;
array.resize(_row);
for(int i = 0; i < _row; i++)
array[i].resize(_col);
}
}
Matrix::Matrix(const Matrix &A)
{
_row = A._row;
_col = A._col;
array.resize(_row);
array[0].resize(_col);
}
void Matrix::print(int row)
{
vector<double> p;
p = array[row];
cout << "[ ";
for(int i = 0; i < _col; i++)
cout << array[row][i] << " ";
cout << "]" << endl;
}
//运算符重载
Matrix& Matrix::operator = (const Matrix& rhs)
{
if (this == &rhs)
return *this;
this->_row = rhs._row;
this->_col = rhs._col;
this->array = rhs.array;
//this->array.resize(_row);
//for (int i = 0; i < rhs._row; i++) {
//
// this->array[i].resize(_col);
//}
//for (int i = 0; i < rhs._row; i++) {
//
// for (int j = 0; j < rhs._col; j++) {
// this->array[i][j] = rhs.array[i][j];
// }
//}
return *this;
}
Matrix& Matrix::operator + (const Matrix& rhs)
{
//Matrix mTemp(_row, _col);
for (int i = 0; i < rhs.array.size(); i++) {
for (int j = 0; j < rhs.array[0].size(); j++) {
double a;
a = this->array[i][j] + rhs.array[i][j];
this->array[i][j] = this->array[i][j] + rhs.array[i][j];
}
}
return *this;
}
void Matrix::add_row_element(int nrow, vector<double> vec)
{
//vector<double>::iterator p;
//p = array.begin();
//row = array.size();
//col = array[0].size();
// for (int i = 0; i < _row; i++) {
// vector<double> row;
if (nrow >= _row || nrow < 0) {
cout << "Out of matrix" << endl;
}
else
{
array[nrow] = vec;
}
// row.push_back(1);
// }
// }
}
未完待续..........