[ create a new paste ] login | about

Link: http://codepad.org/UubGjRqS    [ raw code | output | fork ]

C++, pasted on May 26:
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
class Matrix {
private:
  int *p;
  int x, y;
public:
  Matrix() {
    x = y = 0;
    p = 0;
  }
  Matrix(int a, int b) {
    x = a;
    y = b;
    p = new int [a * b];
    for (int i = 0; i < a; i++)
      for (int j = 0; j < b; j++)
        p[i * b + j] = 0;
  }
  Matrix(const Matrix &a) {
    int i;
    x = a.x;
    y = a.y;
    p = new int [x * y];
    for (i = 0; i < x * y; i++)
      p[i] = a.p[i];
  }
  Matrix &operator=(const Matrix &a) {
    if (x * y < a.x * a.y) {
      delete [] p;
      p = new int [a.x * a.y];
    }
    x = a.x;
    y = a.y;
    for (int i = 0; i < x * y; i++)
      p[i] = a.p[i];
    return *this;
  }
  ~Matrix() {
    delete [] p;
  }
  int &operator[](int i) {
    if (i < 0 || i > x * y) {
      cerr << "out of bounds, abborted." << endl;
      exit(-1);
    }
    return p[i];
  }
  void show() {
    for (int i = 0; i < x; i++) {
      for (int j = 0; j < y; j++)
        cout << p[i * y + j] << ' ';
      cout << endl;
    }
    cout << endl;
  }        
  friend Matrix operator*(Matrix a, Matrix b) {
    Matrix c(a.x, b.y);
    c.x = a.x;
    c.y = b.y;
    for (int i = 0; i < c.x; i++)
      for (int j = 0; j < c.y; j++) {
        c.p[i * c.y + j] = 0;
        for (int k = 0; k < a.y; k++)
          c.p[i * c.y + j] += a.p[i * a.y + k] * b.p[k * b.y + j];
      }
    return c;
  }
};

using namespace std;
int main() {
  int a, b, c;
  cout << "a = "; scanf("%d", &a);
  cout << "b = "; scanf("%d", &b);
  cout << "c = "; scanf("%d", &c);

  Matrix ob1(a, b);
  Matrix ob2(b, c);
  Matrix ob3;

  for (int i = 0; i < a; i++)
    for (int j = 0; j < b; j++)
      ob1[b * i + j] = j + (a - 1) * i;
  for (int i = 0; i < b; i++)
    for (int j = 0; j < c; j++)
      ob2[c * i + j] = j - (b - 1) * i;
  ob1.show();
  ob2.show();
  ob3 = ob1 * ob2;
  ob3.show();
  return 0;
}
/* end */


Output:
1
2
a = b = c = std::bad_alloc: St9bad_alloc
Aborted.


Create a new paste based on this one


Comments: