c++ - 我试图在 Mac OS 上运行 Armadillo ,但我不断收到同样的错误

标签 c++ macos operator-keyword mat armadillo

我正在尝试用文本文件中的数据填充矩阵。

这是我的代码

int main() {

ifstream in;


int n=150;
int m=5;


mat coordinates (n,m);
coordinate.zeros();

in.open("test.txt");

for (int i=0; i<n ; i++) {
    for (int j=0; i<m ; j++)

        in >> coordinates(i,j);

  return 0;
}

我是用命令编译的

g++ -I/usr/local/include 坐标.cpp -O2 -larmadillo -llapack -lblas

到目前为止一切似乎都很好,但是当我尝试运行该程序时出现以下错误

错误:Mat::operator():索引越界 libc++abi.dylib:以 std::logic_error 类型的未捕获异常终止:Mat::operator():索引越界 中止陷阱:6

我尝试了我能想到的一切,但没有任何效果。你有什么建议吗?

感谢您的宝贵时间。

最佳答案

您的代码中存在错误:第二个循环有 i<m而不是 j<m .

此外,不要直接使用 >>运算符与矩阵,因为您无法检查是否实际读取了元素。相反,您可以简单地使用 .load() 加载整个文件。成员函数。

最好通读 Armadillo documentation在发布基本问题之前。

// simple way

mat coordinates;
coordinates.load("test.txt", raw_ascii);   // .load() will set the size
coordinates.print();  

// complicated way

ifstream in;
in.open("test.txt");

unsigned int n=150;
unsigned int m=5;

mat coordinates(n, m, fill::zeros);

for(unsigned int i=0; i<n; ++i)
    {
    for(unsigned int j=0; j<m; ++j)
        {
        double val;
        in >> val;

        if(in.good())  { coordinates(i,j) = val; }
        }
    }

coordinates.print();

关于c++ - 我试图在 Mac OS 上运行 Armadillo ,但我不断收到同样的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34259437/

相关文章:

macos - 如何在 Mac OS 上运行 ./Configure 编译应用程序?

c++ - cin.get() 和 cin.getline() 的区别

java - 如何存储 Java 桌面应用程序(多平台)全局设置?

C++ 大数阶乘

python - 卸载 Canopy Enthought 会留下奇怪的 bash 警告?

bash set -e and i=0;让i++不同意

parsing - 语法与运算符结合性之间的关系

Bash 4.4 提示转义当前正在运行的作业数量

c++ - friend 功能不访问另一个 friend 类的私有(private)成员

c++ - 错误 X8000 : D3D11 Internal Compiler error : Invalid Bytecode: Invalid operand type for operand #1 of opcode #86 (counts are 1-based)