Skip to content

Instantly share code, notes, and snippets.

@DanielUranga
Created June 23, 2017 17:36
Show Gist options
  • Save DanielUranga/39dc9b62e44088d1f23d4d52b5809e2b to your computer and use it in GitHub Desktop.
Save DanielUranga/39dc9b62e44088d1f23d4d52b5809e2b to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cassert>
#include <vector>
template <typename T>
class Matrix
{
public:
explicit Matrix(size_t xs, size_t ys) : xs(xs), ys(ys), cells(xs * ys)
{
}
typedef size_t Row;
typedef size_t Col;
class MatrixRow
{
public:
MatrixRow(Matrix* m, Row row) : m(m), row(row)
{
}
T& get(Col col) const
{
return m->get(row, col);
}
void set(Col col, T val)
{
m->set(row, col, val);
}
size_t getWidth() const
{
return m->getWidth();
}
T& operator[](Col col)
{
return get(col);
}
class MatrixRowIterator
{
public:
MatrixRowIterator(MatrixRow* row, Col col) : row(row), col(col)
{
}
MatrixRowIterator& operator++()
{
++col;
return *this;
}
T operator*()
{
return row->get(col);
}
bool operator!=(const MatrixRowIterator& other)
{
return { row != other.row || col != other.col };
}
private:
MatrixRow* row;
Col col;
};
MatrixRowIterator begin()
{
return MatrixRowIterator(this, 0);
}
MatrixRowIterator end()
{
return MatrixRowIterator(this, getWidth());
}
private:
Matrix* m;
Row row;
};
class MatrixIterator
{
public:
MatrixIterator(Matrix* m, Row row) : m(m), row(row)
{
}
MatrixIterator& operator++()
{
++row;
return *this;
}
MatrixRow& operator*()
{
return m->get(row);
}
bool operator!=(const MatrixIterator& other)
{
return { m != other.m || row != other.row };
}
private:
Matrix* m;
Row row;
};
MatrixIterator begin()
{
return MatrixIterator(this, 0);
}
MatrixIterator end()
{
return MatrixIterator(this, getHeight());
}
size_t getWidth() const
{
return xs;
}
size_t getHeight() const
{
return ys;
}
MatrixRow get(Row y)
{
return MatrixRow(this, y);
}
T& get(Col x, Row y)
{
assert(x < xs && y < ys);
return cells[y * xs + x];
}
void set(Col x, Row y, T val)
{
assert(x < xs && y < ys);
cells[y * xs + x] = val;
}
MatrixRow& operator[](Row row)
{
return get(row);
}
private:
size_t xs;
size_t ys;
std::vector<T> cells;
};
int main()
{
Matrix<int> m(3, 3);
m[0][0] = 1;
m[1][1] = 2;
m[2][2] = 3;
int a = m[2][2];
std::cout << "Seba: " << a << std::endl;
for (auto row : m)
{
for (auto val : row)
{
std::cout << val << " ";
}
std::cout << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment