【问题标题】:How do I stream a file into a matrix in C++ boost ublas?如何将文件流式传输到 C++ boost ublas 中的矩阵中?
【发布时间】:2012-09-16 21:08:57
【问题描述】:

我正在尝试将包含矩阵数据的文件读入提升矩阵。 "" 已经应该对这类事情有运算符重载,我可以让它写入标准流(cout)。我不知道走另一条路有什么问题。我对 C++ 相当陌生,所以我猜我对文件流做出了不正确的假设,但它似乎是有道理的。以下是我要访问的网页:

http://www.boost.org/doc/libs/1_51_0/boost/numeric/ublas/io.hpp

http://www.cplusplus.com/reference/iostream/ifstream/ifstream/

这是我的代码:

using namespace std;
matrix<double> M;
ifstream s("C:\temp\perm.txt", ifstream::in);

s >> M;
s.close();

std::cout << M;

这是我的文件的样子:

[4,4]((0,0,1,0),(0,0,0,1),(0,1,0,0),(1,0,0,0))

【问题讨论】:

  • 您所展示的内容没有任何问题。 Here is a small example I made,有什么问题?
  • @Jesse 但是……ideone 有点奇怪。当我 fork 你的程序时,我收到以下错误 prog.cpp:1:38: fatal error: boost/numeric/ublas/io.hpp: No such file or directory #include &lt;boost/numeric/ublas/io.hpp&gt; - 这是程序 - ideone.com/06Zsrf。什么给了?
  • @lifebalance: ideone 移除了 boost 支持。请改用coliru,因为它支持boost。
  • @JesseGood 谢谢! - 你如何指定 coliru 的标准输入?

标签: c++ boost matrix ifstream ublas


【解决方案1】:

这是一个小例子,请尝试一下,看看会发生什么。如果这不起作用,我怀疑问题是文件路径错误或程序无法从文本文件中读取:

#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <iostream>
#include <fstream>

int main()
{
    boost::numeric::ublas::matrix<double> m;
    std::ifstream s("C:\temp\perm.txt");
    if (!s)
    {
        std::cout << "Failed to open file" << std::endl;
        return 1;
    }
    if (!s >> m)
    {
        std::cout << "Failed to write to matrix" << std::endl;
        return 1;
    }
    std::cout << "Printing matrix: ";
    std::cout << m;
}

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多