Last active
April 24, 2024 12:56
-
-
Save grayed/8eefdbbfa17f8c5461d63ae2fea77ce0 to your computer and use it in GitHub Desktop.
Copy constructor and Co.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <climits> | |
#include <iostream> | |
#include <cstring> | |
#include <new> | |
using namespace std; | |
class Matrix { | |
double *nums; | |
size_t nrows, ncols; | |
public: | |
/// 1. Реализовать методы для получения и перезаписи строки и столбца из vector<double>. | |
/// 2. Реализовать ленивое копирование (с подсчётом ссылок). | |
Matrix(size_t nrows, size_t ncols) : nrows(nrows), ncols(ncols) { | |
if (ncols >= SIZE_MAX / sizeof(double)) | |
throw out_of_range("too large columns count"); | |
nums = static_cast<double*>(calloc(nrows, ncols * sizeof(double))); | |
if (!nums) | |
throw bad_alloc(); | |
} | |
Matrix(const Matrix &m) : nrows(m.nrows), ncols(m.ncols) { | |
auto sz = nrows*ncols*sizeof(double); | |
nums = static_cast<double*>(malloc(sz)); | |
if (!nums) | |
throw bad_alloc(); | |
memcpy(nums, m.nums, sz); | |
} | |
~Matrix() { cerr << "!destructor " << (intptr_t)nums << "!"; free(nums); } | |
Matrix& operator=(const Matrix &m) { | |
if (ncols != m.ncols || nrows != m.nrows) | |
throw out_of_range("matricies do not have same bounds"); | |
memcpy(nums, m.nums, nrows*ncols*sizeof(double)); | |
} | |
double& operator()(size_t row, size_t col) { | |
cerr << '(' << (intptr_t)this << ')'; | |
if (row >= nrows) | |
throw out_of_range("invalid row index"); | |
if (col >= ncols) | |
throw out_of_range("invalid column index"); | |
return nums[row * ncols + col]; | |
} | |
double operator()(size_t row, size_t col) const { | |
cerr << '[' << (intptr_t)this << ']'; | |
if (row >= nrows) | |
throw out_of_range("invalid row"); | |
if (col >= ncols) | |
throw out_of_range("invalid column index"); | |
return nums[row * ncols + col]; | |
} | |
Matrix operator*(double n) const { | |
Matrix m(nrows, ncols); | |
for (size_t row = 0; row < nrows; row++) | |
for (size_t col = 0; col < ncols; col++) | |
m(row, col) = (*this)(row, col) * n; | |
return m; | |
} | |
friend ostream& operator<<(ostream &os, const Matrix &m); | |
}; | |
ostream& operator<<(ostream &os, const Matrix &m) { | |
for (size_t row = 0; row < m.nrows; row++) { | |
for (size_t col = 0; col < m.ncols; col++) | |
os << m(row, col) << ' '; | |
os << endl; | |
} | |
return os; | |
} | |
int main() | |
{ | |
Matrix m1(5, 5); m1(0, 0) = 1; m1(0, 1) = 2; m1(1, 0) = 3; m1(1, 1) = -0.5; | |
cout << m1 << endl; | |
Matrix m2 = m1 * -1.3; | |
cout << m2 << endl; | |
Matrix m3(5, 5); | |
m3 = m2; | |
cout << m3 << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment