如何在初始化期间将std :: initializer_list转换为列矩阵或列向量?

时间:2016-10-27 20:55:54

标签: c++ matrix vector

我有两个课程my_matrixmy_vector。课程my_vector继承自my_matrixmy_matrix类也是由2d std::vector<std::vector<double>>组成的。我想让my_vector成为column vector/column matrix,它基本上是nx1矩阵。

当我尝试按std::initializer_list初始化矩阵时,它可以正常工作

class my_matrix{
    public:
        my_matrix(std::initializer_list<std::vector<double>> list: row(list.size(),
                                   col((*list.begin()).size()), matrix(list){}

    private:
        std::vector<std::vector<double> matrix; // I am planning to use single contiguous memory in future
    };

这允许我初始化矩阵的值   my_matrix mat = {{1,2,3},{4,5,6}};     现在我使用矩阵来创建向量(数学)

    class my_vector: public Matrix{
        my_vector(std::initializer_list<double> list):Matrix({list}){}
        // my_vector(std::initializer_list<double> list)
     //:Matrix({some how I could do  {{list[0]}, {list[1]}, {list[2]}, ..}}){}

    }; 

因此,当我尝试my_vector vec = {1,2,3};时,它会创建一个1xn矩阵,但我想要的是nx1

那么如何确保使用nx1创建std::initializer_list的列矩阵?我还有其他选择可以尝试实现吗?

1 个答案:

答案 0 :(得分:0)

在Nathan的建议之后,我创建了一个新的构造函数作为protected,将std::initializer<double>作为my_matrix类中的参数:

class my_matrix{
    public:
        my_matrix(std::initializer_list<std::vector<double>> list: row(list.size(),
                                   col((*list.begin()).size()), matrix(list){}
    protected:
        my_matrix(std::initializer_list<double> list):row(list.size()), col(1){
            vec_alloc() // allocates appropriate memory for 2d vector
            int r = 0;
            // This loop creates nx1 matrix
            for(auto it = list.begin(); it != list.end(); it++){
                matrix[r][0] = *it;
                r++;
            }
        }
    private:
        std::vector<std::vector<double> matrix; // I am planning to use single contiguous memory in future
};

class my_vector: public Matrix{
public:
    my_vector(std::initializer_list<double> list):Matrix(list){}

};