Skip to content

Instantly share code, notes, and snippets.

@Wizmann
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wizmann/73c41ea02590cd466c1c to your computer and use it in GitHub Desktop.
Save Wizmann/73c41ea02590cd466c1c to your computer and use it in GitHub Desktop.
comma_matrix.cc
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define print(x) do {cout << x << endl;} while(0)
#define input(x) do {cin >> x;} while(0)
template<typename T, int sy, int sx>
class Matrix {
public:
Matrix(): y(sy), x(sx)
{
vec.reserve(x * y);
};
friend ostream& operator<< (ostream& os, Matrix& mat)
{
for (int i = 0; i < mat.y; i++) {
for (int j = 0; j < mat.x; j++) {
os << mat.vec[i * mat.x + j] << ' ';
}
os << '\n';
}
return os;
}
friend Matrix<T, sx, sy>& operator<< (Matrix& mat, const T& it)
{
mat.ptr = 0;
mat.vec[mat.ptr++] = it;
return mat;
}
friend Matrix<T, sx, sy>& operator, (Matrix& mat, const T& it)
{
if (mat.ptr >= mat.x * mat.y) {
print("ERROR!");
}
mat.vec[mat.ptr++] = it;
return mat;
}
private:
int y, x;
int ptr;
vector<T> vec;
};
int main()
{
Matrix<int, 3, 3> mat;
mat << 1, 2, 3,
4, 5, 6,
7, 8, 9;
print(mat);
return 0;
}
// ANOTHER TRY
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define print(x) do {cout << x << endl;} while(0)
#define input(x) do {cin >> x;} while(0)
template<typename T, int sy, int sx>
class Matrix;
template<typename M, typename T>
struct CommaInitializer;
template<typename T, int sy, int sx>
class Matrix {
public:
Matrix(): y(sy), x(sx)
{
vec.reserve(x * y);
};
friend ostream& operator<< (ostream& os, Matrix& mat)
{
for (int i = 0; i < mat.y; i++) {
for (int j = 0; j < mat.x; j++) {
os << mat.vec[i * mat.x + j] << ' ';
}
os << '\n';
}
return os;
}
friend CommaInitializer<Matrix<T, sy, sx>, T> operator<< (Matrix& mat, const T& it)
{
CommaInitializer<Matrix<T, sy, sx>, T> ci(mat);
ci.append(it);
return ci;
}
friend class CommaInitializer<Matrix<T, sy, sx>, T>;
private:
int y, x;
int ptr;
vector<T> vec;
};
template<typename M, typename T>
struct CommaInitializer {
CommaInitializer(M& i_mat): mat(i_mat), ptr(0)
{
// pass
}
M& mat;
mutable int ptr;
int append(const T& it) const
{
if (ptr >= mat.x * mat.y) {
print("ERROR");
return -1;
} else {
mat.vec[ptr++] = it;
}
return 0;
}
friend const CommaInitializer<M, T>& operator, (const CommaInitializer<M, T> &ci, const T& it)
{
ci.append(it);
return ci;
}
};
int main()
{
Matrix<int, 3, 3> mat;
mat << 1 , 2 , 3 ,
4 , 5 , 6 ,
7 , 8 , 9;
print(mat);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment