Created
May 14, 2014 02:07
-
-
Save Experiment5X/ce0d66b0eb2abfe0db72 to your computer and use it in GitHub Desktop.
For future me, when I forget how this works.
This file contains hidden or 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 <iostream> | |
#include <algorithm> | |
using namespace std; | |
class Matrix | |
{ | |
public: | |
// constructor | |
Matrix(int width, int height) : | |
m_width(width), m_height(height) | |
{ | |
m_matrix = new int[m_width * m_height]; | |
std::fill(m_matrix, m_matrix + m_width * m_height, 0); | |
} | |
// copy | |
Matrix(const Matrix &other) | |
{ | |
m_matrix = new int[other.m_width * other.m_height]; | |
std::copy(other.m_matrix, other.m_matrix + other.m_width * other.m_height, m_matrix); | |
} | |
// move | |
Matrix(Matrix &&other) | |
{ | |
// since the rvalue will be destroyed shortly after this code is executed we can steal | |
// the members from it so they don't have to be copied | |
m_matrix = other.m_matrix; | |
other.m_matrix = nullptr; | |
} | |
// destructor | |
~Matrix() | |
{ | |
delete[] m_matrix; | |
} | |
int getAt(int x, int y) const | |
{ | |
return m_matrix[m_width * x + y]; | |
} | |
void setAt(int value, int x, int y) | |
{ | |
m_matrix[m_width * x + y] = value; | |
} | |
int getWidth() const | |
{ | |
return m_width; | |
} | |
void setWidth(int width) | |
{ | |
m_width = width; | |
} | |
int getHeight() const | |
{ | |
return m_height; | |
} | |
void setHeight(int height) | |
{ | |
m_height = height; | |
} | |
private: | |
int *m_matrix; | |
int m_width; | |
int m_height; | |
}; | |
Matrix GenerateMatrix(int width, int height) | |
{ | |
Matrix toReturn(width, height); | |
for (int x = 0; x < width; x++) | |
for (int y = 0; y < height; y++) | |
toReturn.setAt(x * y, x, y); | |
return toReturn; | |
} | |
void PrintMatrix(const Matrix &m) | |
{ | |
for (int x = 0; x < m.getWidth(); x++) | |
{ | |
for (int y = 0; y < m.getHeight(); y++) | |
cout << m.getAt(x, y) << " "; | |
cout << endl; | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
// Instead of performing a copy of the rvalue, it is moved | |
PrintMatrix(GenerateMatrix(5, 5)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment