简体   繁体   中英

Copy constructor of vector<vector> c++

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;
};

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 .

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. Ie

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>>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM