Skip to content

Instantly share code, notes, and snippets.

@JohannesMP
Created November 6, 2016 09:49
Show Gist options
  • Select an option

  • Save JohannesMP/52ea8b4138cee04c0237c84821df4b5d to your computer and use it in GitHub Desktop.

Select an option

Save JohannesMP/52ea8b4138cee04c0237c84821df4b5d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
class Matrix
{
// Helper struct for comma initializer list insertion
struct Matrix_CommaInitializer
{
Matrix_CommaInitializer(Matrix& m, size_t index)
: matrix_(m)
, index_(index)
, range_(m.width_*m.height_)
{}
Matrix_CommaInitializer& operator,(int i)
{
if(index_ >= range_) return *this;
matrix_.vals_[index_/matrix_.width_][index_%matrix_.width_] = i;
index_++;
return *this;
}
Matrix& matrix_;
unsigned index_;
unsigned range_;
};
public:
Matrix(unsigned int w, unsigned int h)
: width_(w)
, height_(h)
, vals_(height_, Matrix_Row(width_, 0))
{}
Matrix_CommaInitializer operator<<(int val)
{
return Matrix_CommaInitializer(*this, 0), val;
}
friend std::ostream& operator<<(std::ostream& os, const Matrix& m);
private:
unsigned int width_;
unsigned int height_;
typedef std::vector<int> Matrix_Row;
std::vector<Matrix_Row> vals_;
};
std::ostream& operator<<(std::ostream& os, const Matrix& m)
{
os << "[\n";
for(const Matrix::Matrix_Row& row : m.vals_)
{
os << " [";
for(int val : row)
{
os << val << ", ";
}
os << "]\n";
}
os << "]";
return os;
}
int main()
{
Matrix m(3,2);
m << 1, 2, 3, 4, 5;
std::cout << "Matrix Contents: \n" << m << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment