c++逐列构造矩阵读取列

标签 c++ matrix sparse-matrix

我想为此实现 CSCmatrix(压缩稀疏列)我需要读取以这种形式给出的矩阵:

{{1,2,3,4},{5,6,7,8}};

逐列阅读!而不是逐行(在这种情况下,我可以使用如下所示的简单构造函数)

template<typename T>
inline constexpr CSRmatrix<T>::CSRmatrix(std::initializer_list<std::initializer_list<T>>&& row ) noexcept
{
    this->rows = row.size();
    auto itr = *(row.begin());
    this->cols = itr.size();

    std::size_t i=0, j=0, w=0;  

    ia_.resize(rows+1);
    ia_[0] = 0;
    for(auto & r : row)
    {
        j=0 ; w =0 ;    
        for(auto & c : r)
        {
           if( c != 0.0 )
           {  
              a_.push_back(c);
             ja_.push_back(j);
             w++;
           }
           j++; 
        }
        i++;
        ia_[i] = ia_[i-1] + w ;
    }
}

这逐行读取并以 CSR 格式(压缩的稀疏行)存储矩阵有人可以帮助我吗?我没有想法 !提前致谢

我的数据将按此顺序存储在单个 vector 中 {1,5,2,6,3,7,4,8}

最佳答案

如果您的数据声明为 vector<vector<T>> data , 你可以简单地把 data(v)在初始化中。但是,如果您想切换行和列,请使用临时变量并切换行和列。

编辑,或使用 arr将数据放在一个数组中

此代码假定初始化数据中的所有行大小相同

template<typename T> class matrix
{
public:
    //std::vector<std::vector<T>> data;
    std::vector<T> arr;
    matrix(std::initializer_list<std::vector<T>> v) //: data(v)
    {
        if(!v.size()) return; //invalid input
        std::vector<std::vector<T>> temp(v);
        //test to make sure all row are the same size
        //use the size of row[0] for all other rows:
        for(size_t c = 0; c < temp[0].size(); c++)
        {
            for(size_t r = 0; r < temp.size(); r++)
            {
                if(c < temp[r].size())
                    arr.push_back(temp[r][c]);
                //else {invalid input}
            }
        }
        for(size_t c = 0; c < temp[0].size(); c++)
            for(size_t r = 0; r < temp.size(); r++)
                arr.push_back(temp[r][c]);
    }
};

int main()
{
    matrix<int> m = { { 1,2,3,4 },{ 5,6,7,8 } };
    for(auto e : m.arr) std::cout << e << ",";
    std::cout << "\n";
    return 0;
}

输出

1,5,2,6,3,7,4,8,

关于c++逐列构造矩阵读取列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197046/

相关文章:

algorithm - m 对角 NxN 对称矩阵行列式的高效算法

c++ - 如何处理 WM_NCCALCSIZE 并制作类似 chrome 的界面?

python - 结果稀疏性已知时的稀疏矩阵乘法(在 python|scipy|cython 中)

ruby - 在二维数组中注入(inject)增量计数器

MATLAB,如何在不超过内存限制的情况下计算大坐标集之间的距离?

python - sparse_csc 矩阵的索引在提取一些列后反转

python - csr_matrix 的点积导致段错误

二级类不可读的 C++ 私有(private)变量

c++ - 如何在多个函数之间传递 vector ?

c++ - MySQL 连接器 8.0 C++ 错误 : "CDK: Failed string conversion"