Last active
August 29, 2015 14:09
-
-
Save m-renaud/34547568d7ab580a3021 to your computer and use it in GitHub Desktop.
Simple Matrix addition in C++.
This file contains 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 <vector> | |
using std::vector; | |
// Represents a matrix with the contents stored in row major order. | |
struct Matrix { | |
int numRows; | |
int numColumns; | |
vector<vector<int>> contents; | |
}; | |
// Construct a Matrix from a list of rows. | |
Matrix ToMatrix(const vector<vector<int>>& contents) { | |
return {contents.size(), contents[0].size(), contents}; | |
} | |
// Add two matricies 'a' and 'b' together. | |
Matrix Add(const Matrix& a, const Matrix& b) { | |
Matrix c; | |
c.numRows = a.numRows; | |
c.numColumns = b.numColumns; | |
for (int r = 0; r < a.numRows; ++r) { | |
vector<int> row; | |
for (int c = 0; c < a.numColumns; ++c) { | |
row.push_back(a.contents[r][c] + b.contents[r][c]); | |
} | |
c.contents.push_back(row); | |
} | |
return c; | |
} | |
// Write a Matrix to an output stream. | |
std::ostream& operator <<(std::ostream& os, const Matrix& a) { | |
os << "Matrix {numRows = " << a.numRows | |
<< ", numColumns = " << a.numColumns | |
<< ", contents = ["; | |
for (const vector<int>& row : a.contents) { | |
os << "[ "; | |
for (int e : row) { | |
os << e << " "; | |
} | |
os << "]"; | |
} | |
os << "]"; | |
return os; | |
} | |
int main() { | |
Matrix a = ToMatrix({{1,2,3},{4,5,6}}); | |
Matrix b = ToMatrix({{1,1,1},{2,2,2}}); | |
std::cout << Add(a,b) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment