0

I'm trying to pass a 2x2 matrix to a constructor like this:

Matrix test =   {{ 1, 2},
                { 5, 6}};

What would the constructor look like?

 Matrix(?)

The answer in the linked questions did not sufficiently explain how they solved their original problem. I was lost in their generic array answer and am not sure how to use their solution for conventional types.

Cool Guy
  • 1
  • 1
  • 1
    Don't expect everything to be valid C++. Nevertheless, look for `initializer_list`. – user202729 Mar 26 '18 at 01:02
  • 2
    Possible duplicate of [is there a way to pass nested initializer lists in C++11 to construct a 2D matrix?](https://stackoverflow.com/questions/15810171/is-there-a-way-to-pass-nested-initializer-lists-in-c11-to-construct-a-2d-matri) – user202729 Mar 26 '18 at 01:03
  • I didn't really understand the answer when he made it generic. – Cool Guy Mar 26 '18 at 05:08
  • From [ask]: "_Even if you don't find a useful answer elsewhere on the site, including links to related questions that haven't helped can help others in understanding how your question is different from the rest._" You should _explain_ in the question (for example by [edit]ing the question) what _exactly_ can't you understand. – user202729 Mar 26 '18 at 05:31
  • I don't understand how the user's edited solution answered their original question. – Cool Guy Mar 26 '18 at 05:35

1 Answers1

0

If you want to only 2x2 or specified mxn matrix and to use simply, try this. It can work your initialization style, too. (C++11 build)

#include <iostream>
#include <vector>

class Row2 {
public:
    int a1, a2 ;
    Row2(int a1, int a2) : a1(a1), a2(a2) {}
    void print() {
        std::cout << a1 << "," << a2 << std::endl ;
    }
};

class Matrix2 {
public:
    Row2 r1, r2 ;
    Matrix2(Row2 r1, Row2 r2) : r1(r1),r2(r2) {}
    void print() {
        r1.print() ;
        r2.print() ;
    }
} ;

int main() {
    std::vector<Row2> mat2 { {1,2}, {3,4} } ;
    for (auto r : mat2 ) {
        r.print() ;
    }

    Matrix2 mat { {5,6},{7,8} };
    mat.print() ;

    return 0 ;
}
Junhee Shin
  • 748
  • 6
  • 8