Skip to content

Instantly share code, notes, and snippets.

@tforgione
Last active May 9, 2017 10:00
Show Gist options
  • Save tforgione/97c8e3d76ff4b739a14fc0be3099994d to your computer and use it in GitHub Desktop.
Save tforgione/97c8e3d76ff4b739a14fc0be3099994d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <algorithm>
namespace my {
template<typename T>
struct matrix;
namespace priv {
template<typename T>
struct matrix_iterator {
matrix_iterator() : m_row(0), m_col(0), m_matrix() {}
matrix_iterator(matrix<T>& matrix, std::size_t row, std::size_t col) :
m_row(row), m_col(col), m_matrix(&matrix) {
}
matrix_iterator(matrix_iterator<T> const& other) :
m_row(other.m_row), m_col(other.m_col), m_matrix(other.m_matrix) {
}
~matrix_iterator() {
}
matrix_iterator<T>& operator=(matrix_iterator<T> const& other) {
m_matrix = other.m_matrix;
m_row = other.m_row;
m_col = other.m_col;
return *this;
}
matrix_iterator<T>& operator++() {
if (m_col == m_matrix->m_col_number - 1) {
m_col = 0;
m_row++;
} else {
m_col++;
}
return *this;
}
matrix_iterator<T> operator++(int) {
matrix_iterator<T> copy = *this;
++*this;
return copy;
}
T& operator*() {
return (*m_matrix)(m_row, m_col);
}
bool operator==(matrix_iterator<T> const& other) const {
return m_matrix == other.m_matrix && m_row == other.m_row && m_col == other.m_col;
}
bool operator!=(matrix_iterator<T> const& other) const {
return !(*this == other);
}
std::size_t m_row;
std::size_t m_col;
matrix<T>* m_matrix;
};
}
template<typename T>
struct matrix {
// For iterators
typedef priv::matrix_iterator<T> iterator;
typedef std::pair<std::size_t, std::size_t> size_type;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
matrix(std::size_t row_number, std::size_t col_number) :
m_row_number(row_number), m_col_number(col_number), m_data(row_number * col_number) {
}
reference operator()(std::size_t i, std::size_t j) {
return m_data[i * m_col_number + j];
}
iterator begin() {
return iterator(*this, 0, 0);
}
iterator end() {
return iterator(*this, m_row_number, 0);
}
std::size_t m_row_number;
std::size_t m_col_number;
std::vector<T> m_data;
};
}
int main(int argc, char *argv[])
{
std::cout << std::boolalpha;
my::matrix<float> m{3, 4};
m(1, 2) = 3;
for (auto elt : m) {
// This compiles successfully
}
auto max = std::max_element(m.begin(), m.end());
std::cout << "max is (" << max.m_row << ',' << max.m_col << ") = " << *max << std::endl;
// Test C++ iterators
std::vector<int> v1{1,2,3}, v2{0, 1};
std::vector<int>::iterator iterator = std::begin(v2);
iterator = std::end(v1);
iterator--;
std::cout << std::distance(v1.begin(), iterator) << " -> " << *iterator << std::endl;
std::cout << (std::begin(v1) == std::begin(v2)) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment