Skip to content

Instantly share code, notes, and snippets.

@Zorgatone
Last active February 23, 2017 14:37
Show Gist options
  • Save Zorgatone/53d2173caf2ac0dc3902b7710e8043a2 to your computer and use it in GitHub Desktop.
Save Zorgatone/53d2173caf2ac0dc3902b7710e8043a2 to your computer and use it in GitHub Desktop.
Matrix in C++11/C++14 using unique_ptr and make_unique
#include <iostream>
#include <memory>
#include "Matrix.hpp"
using namespace std;
using namespace zgt;
constexpr size_t num_elements{ 3};
int main() {
Matrix m{ num_elements }; // Squared matrix
double inc{ 1 };
for (size_t i{ 0 }; i < num_elements; i++) {
for (size_t j{ 0 }; j < num_elements; j++) {
m[i][j] = inc++;
}
}
for (size_t i{ 0 }; i < num_elements; i++) {
for (size_t j{ 0 }; j < num_elements; j++) {
if (j == 0) {
cout << m[i][j];
} else {
cout << ", " << m[i][j];
}
}
cout << endl;
}
return 0;
}
#include "Matrix.hpp"
using namespace std;
using namespace zgt;
struct Matrix::_impl {
unique_ptr<unique_ptr<MatrixRow>[]> _m;
_impl(size_t rows, size_t cols): _m(make_unique<unique_ptr<MatrixRow>[]>(rows)) {
for (size_t i{ 0 }; i < cols; i++) {
_m[i] = make_unique<MatrixRow>(cols);
}
}
};
MatrixRow& Matrix::operator[](size_t index) {
return *(pimpl->_m[index]);
}
Matrix::Matrix(size_t rows, size_t cols) : pimpl(make_unique<_impl>(rows, cols)) {}
Matrix::Matrix(size_t size) : Matrix::Matrix(size, size) {}
Matrix::~Matrix() = default;
#pragma once
#ifndef Matrix_hpp
#define Matrix_hpp
#include <iostream>
#include <memory>
#include "MatrixRow.hpp"
namespace zgt {
class Matrix{
struct _impl;
std::unique_ptr<_impl> pimpl;
public:
Matrix(size_t rows, size_t cols);
Matrix(size_t size); // [size][size]
~Matrix();
MatrixRow& operator[](size_t index);
};
}
#endif
#include "MatrixRow.hpp"
using namespace std;
using namespace zgt;
struct MatrixRow::_impl {
unique_ptr<double[]> _v;
_impl(size_t cols): _v(make_unique<double[]>(cols)) {}
};
double& MatrixRow::operator[](size_t index) {
return pimpl->_v[index];
}
MatrixRow::MatrixRow(size_t cols) : pimpl(make_unique<_impl>(cols)) {}
MatrixRow::~MatrixRow() = default;
#pragma once
#ifndef MatrixRow_hpp
#define MatrixRow_hpp
#include <iostream>
#include <memory>
namespace zgt {
class MatrixRow{
struct _impl;
std::unique_ptr<_impl> pimpl;
public:
MatrixRow(size_t cols);
~MatrixRow();
double& operator[](size_t index);
};
}
#endif
@Zorgatone
Copy link
Author

Zorgatone commented Feb 22, 2017

Output:

1, 2, 3
4, 5, 6
7, 8, 9

@Zorgatone
Copy link
Author

Zorgatone commented Feb 23, 2017

To do:

  • Add template for generic type instead of double

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment