I wrote my own matrix class with fields like this
template <typename T>
class Matrix
{
private:
T *data = nullptr;
size_t rows;
size_t cols;
....
I tried to make an iterator for my matrix, but it didn't work. An error like this is thrown in method Iterator begin(and end):
error: cannot convert ‘myMatrix::Matrix<int>::Iterator’ to ‘int*’ in return
The iterator must support STL functions such as std::find_if(). How can I fix the iterator so that it works correctly?
class Iterator
{
friend Matrix;
private:
T *curr;
public:
using iterator_category = std::input_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = value_type *;
using reference = value_type &;
Iterator() : curr(nullptr) {}
Iterator(T *other) : curr(other) {}
~Iterator() = default;
bool operator==(const Iterator &it) const { return curr == it.curr; }
bool operator!=(const Iterator &it) const { return !(curr == it.curr); }
Iterator &operator++()
{
++curr;
return *this;
}
Iterator operator++(int)
{
Iterator temp = *this;
operator++();
return temp;
}
Iterator &operator+(int n)
{
for (int i = 0; i < n; i++)
{
++(*this);
}
return *this;
}
T &operator*() const { return *curr; }
T *operator->() const { return curr; }
};
Iterator begin()
{
Iterator it(data);
return it;
}
Iterator end()
{
Iterator it(data + rows * cols);
return it;
}