Advertisement
Guest User

matrixes

a guest
Jun 3rd, 2014
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. //Hello, I am still having problem with leaks.
  2. //Caused by createNew method and passing reference argument
  3.  
  4. #include <cstdlib>
  5. #include <cstdlib>
  6. #include <cmath>
  7. #include <vector>
  8. #include <iostream>
  9. #include <fstream>
  10. #include <cstring>  
  11. #include <sstream>
  12. #include <map>
  13. using namespace std;
  14.  
  15. class GeneralMatrix {
  16. protected:
  17.     int width;
  18.     int height;
  19.  
  20. public:
  21.  
  22.     //Stores values of matrix size
  23.     GeneralMatrix(int nr, int nc) {
  24.         height = nr;
  25.         width = nc;
  26.     }
  27.     virtual ~GeneralMatrix(){
  28.     }
  29.  
  30.     GeneralMatrix & add(const GeneralMatrix & m2) {
  31.         //Check for compatible matrixes
  32.         if (height != m2.height || width != m2.width) {
  33.             cout << "Matrix sizes must match!" << endl;
  34.             return *this;
  35.         }
  36.         //Create new empty matrix
  37.         GeneralMatrix &m3 = createNew(height, width);
  38.         //Set every number to sum of this and given matrix
  39.         for (int i = 0; i < height; i++) {
  40.             for (int j = 0; j < m2.width; j++) {
  41.                 double val = m2.get(i, j);
  42.                 if (val != 0) {
  43.                     val += get(i, j);
  44.                     m3.set(i, j, val);
  45.                 }
  46.             }
  47.         }
  48.         return m3;
  49.     }
  50. };
  51.  
  52. class RegularMatrix : public GeneralMatrix {
  53. protected:
  54.     vector<double>data;
  55.  
  56. public:
  57.     //Constructor
  58.     RegularMatrix(int nr, int nc, const vector<double>& nums) : GeneralMatrix(nr, nc) {
  59.         data = nums;
  60.     }
  61.  
  62.     GeneralMatrix & createNew(int row, int col) {
  63.         int n = row*col;
  64.         //Prepare vector of zeros
  65.         vector<double>zeros;
  66.         for (int i = 0; i < n; i++) {
  67.             zeros.push_back(0);
  68.         }
  69.         //Call constructor
  70.         GeneralMatrix *ret = new RegularMatrix(row, col, zeros);
  71.         return *ret;
  72.     }
  73.  
  74.  
  75. };
  76.  
  77. int main(int argc, char** argv) {
  78.  double mm3[] = {10, 2, 3, 0, 0, 8, 0, 4, 2, 2, 6, 0, 0, 0, 0, 5};
  79.  vector<double>k;
  80.  
  81.  for (int i = 0; i < 16; i++) {
  82.      k.push_back(mm3[i]);
  83.  
  84.  }
  85.  GeneralMatrix *d = new RegularMatrix(4, 4, k);
  86.  
  87.  (*d).add(*d);
  88.  delete d;
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement