Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include "Matrix.h"
- int main() {
- const int m = 3, n = 4;
- Matrix<int, m, n> a;
- int k = 1;
- std::cout << "Matrix:" << std::endl;
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- a[i][j] = i * j * (k *= -1);
- std::cout << a[i][j] << ' ';
- }
- std::cout << std::endl;
- }
- std::cout << std::endl << "Positive elements of matrix:";
- for (int elem : a) {
- std::cout << ' ' << elem;
- }
- std::cout << std::endl << "Positive elements of matrix (reversed order):";
- for (auto elem = a.end()--; elem != a.begin(); elem--) {
- std::cout << ' ' << *elem;
- }
- std::cout << std::endl;
- return 0;
- }
- #include <iterator>
- #include <vector>
- template <typename T, int m, int n>
- class Matrix {
- private:
- std::vector<T> matrix;
- public:
- Matrix(): matrix(m * n) {
- }
- class Row {
- private:
- std::vector<T>& matrix;
- int rowIndex;
- public:
- Row(std::vector<T>& matrix, int rowIndex): matrix(matrix), rowIndex(rowIndex) {
- }
- T& operator [] (int columnIndex) {
- return matrix[rowIndex * n + columnIndex];
- }
- };
- Matrix::Row operator [] (int rowIndex) {
- return Row(matrix, rowIndex);
- }
- class PositiveIterator: public std::iterator<std::forward_iterator_tag, int, ptrdiff_t, T*, T> {
- private:
- bool isDefault = true;
- std::vector<T>& matrix;
- int index;
- void findNext() {
- do {
- index++;
- } while (index < matrix.size() && matrix[index] <= 0);
- isDefault = index == matrix.size();
- }
- void findPrevious() {
- do {
- index--;
- } while (index >= 0 && matrix[index] <= 0);
- isDefault = index == -1;
- }
- public:
- PositiveIterator(std::vector<T>& matrix, bool isDefault): isDefault(false), matrix(matrix) {
- index = isDefault ? m * n : -1;
- }
- bool operator == (PositiveIterator other) {
- return (isDefault && other.isDefault) || (index == other.index);
- }
- bool operator != (PositiveIterator other) {
- return !(*this == other);
- }
- T& operator * () {
- if (isDefault) {
- throw "not initialized iterator";
- }
- switch (index) {
- case -1:
- findNext();
- break;
- case m * n:
- findPrevious();
- break;
- }
- return matrix[index];
- }
- PositiveIterator& operator ++ () {
- if (isDefault) {
- throw "not initialized iterator";
- }
- findNext();
- return *this;
- }
- PositiveIterator& operator ++ (int) {
- PositiveIterator& tmp = *this;
- operator++();
- return tmp;
- }
- PositiveIterator& operator -- () {
- if (isDefault) {
- throw "not initialized iterator";
- }
- findPrevious();
- return *this;
- }
- PositiveIterator& operator -- (int) {
- PositiveIterator& tmp = *this;
- operator--();
- return tmp;
- }
- };
- PositiveIterator begin() {
- return PositiveIterator(matrix, false);
- }
- PositiveIterator end() {
- return PositiveIterator(matrix, true);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement