每次尝试创建稀疏矩阵时行为都不同

时间:2018-11-08 22:55:52

标签: c++ eigen

我正在尝试从Triplets创建一个稀疏矩阵。某种程度上,下面的程序要么打印仅包含零的矩阵,要么得到

  

^ [[引发'std :: bad_alloc'实例后终止调用
  what():std :: bad_alloc中止。

当我在注释处添加代码时,它有时会开始工作,有时我只会得到零。

我不了解这种行为。似乎与内存有关,但是为什么打印输出内容(在底部的代码中注释之后)会改变顶部的内容呢?

我的方法有问题吗?还是我的设置可能有问题?我刚刚从http://eigen.tuxfamily.org下载了最新的稳定版本。

#include <iostream>
#include <Eigen/SparseCore>
#include <Eigen/Dense>
int main() 
{
    int n = 10; 
    std::vector<Eigen::Triplet<double> > ijv; 
    for(int i; i < n; i++)
    {
        ijv.push_back(Eigen::Triplet<double>(i,i,1));
        if(i < n-1)
        {
            ijv.push_back(Eigen::Triplet<double>(i+1,i,-0.9));
        }
    }

    Eigen::SparseMatrix<double> X(n,n);
    X.setFromTriplets(ijv.begin(), ijv.end());
    std::cout << Eigen::MatrixXd(X) << std::endl;

/*    std::cout << "Row\tCol\tVal" <<std::endl;
    for (int k=0; k < X.outerSize(); ++k)
    {
        for (Eigen::SparseMatrix<double>::InnerIterator it(X,k); it; ++it)
        {
         std::cout << it.row() << "\t"; // row index
         std::cout << it.col() << "\t"; // col index (here it is equal to k)
         std::cout << it.value() << std::endl;
        }
    }
*/


}

0 个答案:

没有答案
相关问题