In the following program mat(i, j)
indexing isn't working in Matrix
class:
#include <iostream>
#include <stdexcept>
class Vector {
private:
int size;
double* data;
public:
// Constructor
Vector() : size(0), data(nullptr) {}
Vector(int s) : size(s), data(new double[s])
{
//std::cout << "Hello, Vector!";
}
~Vector() {
delete[] data;
}
// Copy constructor
Vector(const Vector& other) : size(other.size), data(new double[other.size]) {
for (int i = 0; i < size; i++) {
data[i] = other.data[i];
}
}
// Copy assignment operator
Vector& operator=(const Vector& other) {
if (this != &other) {
delete[] data;
size = other.size;
data = new double[size];
for (int i = 0; i < size; i++) {
data[i] = other.data[i];
}
}
return *this;
}
// Accessor methods
int getSize() const {
return size;
}
double& operator[](int i) {
return data[i];
}
};
class Matrix {
private:
int rows;
int cols;
Vector* data;
public:
// Constructor
Matrix() : rows(0), cols(0), data(nullptr) {}
// Constructor
Matrix(int rows_, int cols_) : rows(rows_), cols(cols_), data(new Vector[rows_]) {
for (int i = 0; i < rows_; i++) {
data[i] = Vector(cols_);
}
}
// Destructor
~Matrix() {
delete[] data;
}
// Copy constructor
Matrix(const Matrix& other) : rows(other.rows), cols(other.cols), data(new Vector[other.rows]) {
for (int i = 0; i < rows; i++) {
data[i] = other.data[i];
}
}
// Copy assignment operator
Matrix& operator=(const Matrix& other) {
if (this != &other) {
delete[] data;
rows = other.rows;
cols = other.cols;
data = new Vector[rows];
for (int i = 0; i < rows; i++) {
data[i] = other.data[i];
}
}
return *this;
}
// Accessor methods
int getRows() const {
return rows;
}
int getCols() const {
return cols;
}
double &operator()(int i, int j) {
return data[i][j];
}
Matrix transpose() const {
Matrix result(cols, rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result(j, i) = data[i][j];
}
}
return result;
}
void print(){
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << data[i][j] << " ";
}
std::cout << std::endl;
}
}
};
int main(){
Matrix m(2, 3);
m(0,0) = 1; m(0,1) = 2; m(0,2) = 3;
m(1,0) = 4; m(1,1) = 5; m(1,2) = 6;
m.print();
Matrix result = m.transpose();
result.print();
if(m(0,1) != 4){
std::cout<<"Indexing is not working";
std::cout<<std::endl;
}
}
Output:
$ sh -c make -s
$ ./main
1 2 3
4 5 6
1 4
2 5
3 6
Indexing is not working
What is missing here?