I am writing custom class Matrix using two-dimensional std::vector. So the problem is that I need to overload ++ operation for iterators so that I can run through the entire matrix at a time.
template <typename T>
class Matrix {
private:
std::vector<std::vector<T>> arr;
public:
Matrix(const std::vector<std::vector<T>>& tmp) {
arr = tmp;
}
std::pair<size_t, size_t> size() const {
std::pair<size_t, size_t> tmp;
if (arr.empty()) {
tmp.first = 0;
tmp.second = 0;
} else {
tmp.first = arr.size();
tmp.second = arr[0].size();
}
return tmp;
}
T operator () (size_t i, size_t j) const {
return arr[i][j];
}
Matrix& transpose() {
std::vector<std::vector<T>> tmp(size().second, std::vector<T>(size().first));
for (size_t i = 0; i < size().first; ++i) {
for (size_t j = 0; j < size().second; ++j) {
tmp[j][i] = arr[i][j];
}
}
*this = Matrix(tmp);
return *this;
}
Matrix transposed() const {
std::vector<std::vector<T>> tmp(size().second, std::vector<T>(size().first));
for (size_t i = 0; i < size().first; ++i) {
for (size_t j = 0; j < size().second; ++j) {
tmp[j][i] = arr[i][j];
}
}
return Matrix(tmp);
}
typename std::vector<T>::iterator begin() {
return arr[0].begin();
}
typename std::vector<T>::iterator end() {
return arr[size().first-1].end();
}
};
For example, with the matrix mat = {{1,2},{3,4}}, this should work:
vector<vector<int>> arr = {{1,2},{3,4}};
Matrix mar(arr);
auto it = mat.begin();
while (it != mat.end()) {
cout << *it << " ";
}
and the output should be:
1 2 3 4
Can you please help me how to overload operator++()
, begin()
and end()
for std::vector
iterators?