Can anyone help me out finding why the sum of my matrices is not how they should be?
template <typename T>
Matrix<T> Matrix<T>::operator + (const Matrix<T> &M){
Matrix<T> tmp(m,n,M.x);
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
tmp.Mat[i][j]+= Mat[i][j]+ M.Mat[i][j];
return tmp;
}
This is my program's body:
#include <iostream>
#include <vector>
template <typename T>
class Matrix {
private:
unsigned int m; unsigned int n;
std::vector<T> x;
std::vector<T> y;
std::vector<std::vector<int>> Mat;
public:
Matrix (unsigned int m, unsigned int n, std::vector<T> x);
Matrix (const Matrix<T> &M); //= default;
// Matrix ();
Matrix<T> operator = (const Matrix<T> &M); // Assignment
Matrix<T> operator + (const Matrix<T> &M); // Addition
Matrix<T> operator - (const Matrix<T> &M); // Subtraction
Matrix<T> operator * (const T &scalar); // Scalar Multiplication
Matrix<T> operator * (const Matrix<T> &M); // Matrix Multiplication
friend std::ostream& operator << (std::ostream& os, const Matrix<T> &M){
for (int i = 0; i< M.m; i++){
for (int j = 0; j< M.n; j++){
os << M.Mat[i][j] << ' ';
}
os << '\n';
}
os << '\n' ;
return os;
}
};
template <typename T>
Matrix<T>::Matrix (unsigned int m, unsigned int n, std::vector<T> x){ //constructor
this -> m = m;
this -> n = n;
this -> x = x;
int index = 0;
Mat.resize(m);
for (unsigned int i = 0; i < Mat.size(); i++) {
Mat[i].resize(n);
}
for (unsigned int i = 0; i<m; i++){
for (unsigned int j = 0; j<n; j++){
Mat[i][j] = x[index];
index++;
}
}
}
template<typename T>
Matrix<T>::Matrix(const Matrix &M) //copy constructor
:
m(M.m),
n(M.n),
Mat(M.Mat)
{}
And this is my main: Note: We were required in the initialization that the constructor should take in 2 unsigned integers and a linear container where the elements will be divided to rows and columns according to the inputted.
int main(){
std::vector<int> x = {1,2,3,4};
std::vector<int> y = {5,6,7,8};
std::vector<int> z = {9,10,11,12};
Matrix<int> A{2,2,x};
Matrix<int> B{2,2,y};
Matrix<int> C{2,2,z};
C = B;
std::cout << "A\n" << A;
std::cout << "B\n" << B;
std::cout << "C\n" << C;
Matrix<int> E(A + B);
std::cout << "E\n" << E;
}
When I add A and B I always get 11 14 17 20
It's like the matrix B doubles before adding to A
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire