mercredi 26 septembre 2018

ostream not printing the result of adding two valarrays (using operator overloading)

So i am still learning about operator overloading and wanted to add two matrices using valarrays, but when i print their addition nothing happens, so here is the code.

// A structure to store a matrix
                struct matrix
                {
                     valarray<int> data;  //valarray that will simulate matrix
                     int row, col;
                };

                  matrix operator+  (matrix mat1, matrix mat2);
        int main()
        {
          int data1 [] = {1,2,3,4,5,6,7,8};
          int data2 [] = {13,233,3,4,5,6,7,8};

          matrix mat1, mat2,ans;
          createMatrix (4, 2, data1, mat1);
          createMatrix (4, 2, data2, mat2);
          cout<<mat1+mat2;
          return 0;
    }
   //Creating the matrix
void createMatrix (int row, int col, int num[], matrix& mat) {
  mat.row = row;
  mat.col = col;
  mat.data.resize (row * col);
  for (int i = 0; i < row * col; i++)
    mat.data [i] = num [i];

}
ostream& operator<< (ostream& out, matrix mat)
{

    for(int i=0;i<mat.col*mat.row;++i)
    {
        out<<mat.data[i]<<" ";
        if( (i+1)%mat.col==0 )
            cout<<endl;
    }
    return out;
}
 // Adding them
matrix operator+(matrix mat1, matrix mat2)
{
    matrix ans;
    ans.data.resize(mat1.row*mat1.col);
    for(int i=0;i<mat1.row*mat1.col;++i)
    {
        ans.data[i]=(mat1.data[i]+mat2.data[i]);
    }
    return ans;
}

There seem to be no error but when i run this it prints nothing, any help would be apprecitated, thanks in advance.

Aucun commentaire:

Enregistrer un commentaire