+ 3

# [ANSWERED] Using a range-based for loop with a custom Matrix class...

I wish to iterate over the elements in the foll. class using a range based for loop as opposed to a regular one. https://code.sololearn.com/cq24J951TxgI/?ref=app I basically want to get this : Matrix<M> M1; for(vector<M> elm : M1); Now, I found that the basic declaration of this loop may look like : for(auto it=begin(M1);it!=end(M1);it++) { elm = *it } Now, what all do I need to declare besides begin and end? Will I have to change my 2D pointer to a vector of vectors for this? Or is there another way?

4 Answers

+ 1

you gonna need begin, end, operator++, operator*, operator!= . thats kinda the basic if i did not forget anything :). Then for full functionality you gonna need a lot more copy constructor move constructor and so on. Why not just inherit std vector and design your matrix to be vectors of vectors then you have already the most things implemented?

+ 3

If I decide to continue using the 2D pointer, will I have to overload the *operator as well for converting a pointer array to a vector? Please guide me on this...

+ 2

@Ozren Zaric
Thank you very much for your reply. Ill use a vector of vectors then. But can you tell me how to implement begin and end for a vector of vectors? Will I have to declare them as friend functions? And how will the definitions look like?
Are these correct?
friend vector<vector<M>::iterator begin
(const Matrix& obj)
{
return obj.mat.begin();
}
friend vector<vector<M>::iterator end
(const Matrix& obj)
{
return obj.mat.end();
}
Also, is that all I need? Or do I need to overload the ++ operator as well now?

+ 2

std::vector already has everything you need (begin end etc)
so just do this
...
template<typename _T>
using Matrix = std::vector<std::vector<_T>>;
int main ()
{
Matrix<double> A{{1,2},{3,4}};
for(auto &row: matrix)
for(auto &entry : row)
std::cout << entry << std::endl;
return 0;
}
( not tested)