0

So i have this class that represtents matrix in my header file. My question is how do i initialize my org_matrix by already created matrix for example:

Matrix_t m{
        {INF, 10, 8,   19, 12},
        {10, INF, 20,  6,  3},
        {8,   20, INF, 4,  2},
        {19,  6,  4, INF,  7},
        {12,  3,  2,   7, INF}
};

Can i define a copy constructor of that object?

using Matrix_t = std::vector<std::vector<double>>;

class Matrix{
public:
    Matrix(const Matrix_t& m);
private:
    Matrix_t org_matrix;
};
1
  • Matrix(const Matrix&) = default; does the job. (you should then also add operator=(const MAtrix&) and move version). Commented Nov 5, 2019 at 9:24

2 Answers 2

2

Matrix(const Matrix_t& m); is not a copy constructor, just a constructor that takes Matrix_t.

Thanks to std::vector copy constructor, its code is very simple:

Matrix(const Matrix_t& m) : org_matrix(m)
{}

However, using std::vector<std::vector<double>> for a matrix is not a good idea. Use single std::vector<double> and then calculate an index in this "flattened" array as row * cols() + col or col * rows() + row.

Sign up to request clarification or add additional context in comments.

4 Comments

Thx for the edit. But I disagree on a vector of vectors not being a good idea. It is not most efficient, but very easy to use. So it all depends on the purpose.
@JHBonarius, raw pointers are also very easy to use, but we still should prefer smart ones. Not always. People should not pick bad habits from the very beginning. In some simple cases vector<vector<..>> can be used to represent a matrix, but in general it is a bad idea that should be warned about. This question might be found later by someone else.
then maybe elaborate on /why/ it is a bad idea ;) p.s. a non-owning raw pointer to the data object of a smart pointer is still common use... or std::ref_wrapper<std::unique_ptr<T>> or so, which imho is effectively the same...
@JHBonarius, a raw pointer is a perfect tool, when used appropriately. I do not suggest to replace every raw pointer by a smart one. But many beginners definitely use raw pointers more often than they should. As for nested vectors, I guess it's a separate question. Good answers can be found here and here.
1

Of course! Why wouldn't you? But Matrix_t is the type of an internal data stage object. A copy constructor should copy from an object of the same class. I.e.

Matrix(const Matrix& m);

... actually Matrix_t should be an internal, private type. You are probably looking for an initializer list constructor.

Matrix(initializer_list<initializer_list<double>>);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.