C++ Armadillo : double for loop using iterators

标签 c++ armadillo

在双 for 循环中使用迭代器的最佳方式是什么。对于单个循环,显而易见的方法似乎是:

arma::vec test = arma::ones(10);
for(arma::vec::iterator i = test.begin(); i != test.end(); ++i){
   int one = *i;
}

所以我想改造以下内容:

arma::mat test = arma::ones(10,10);
for (int i = 0; i < test.n_rows; i++){
 for (int j = 0; j < test.n_cols; j++){
  int one = test(i,j);
 }
}

使用迭代器而不是整数索引。感谢您的建议。

最佳答案

建议在访问矩阵中的元素时仍使用单个循环。 Armadillo 将数据存储在 column-major格式(为了与 LAPACK 兼容),因此迭代器将沿着矩阵中的每一列移动。

arma::mat A(4, 5, arma::fill::randu);
A.print("A:");

// C++98 

arma::mat::iterator it_end = A.end();

for(arma::mat::iterator it = A.begin(); it != it_end; ++it)
   {
   std::cout << (*it) << std::endl;
   }

// C++11

for(const auto& val : A)
   {
   std::cout << val << std::endl;
   }

如果您真的想使用双循环,请使用 .begin_col().end_col() :

// C++11

for(arma::uword c=0; c < A.n_cols; ++c)
  {
  auto it_end = A.end_col(c);

  for(auto it = A.begin_col(c); it != it_end; ++it)
    {
    std::cout << (*it) << std::endl;
    }
  }

最后,.for_each()函数是使用迭代器的替代方法:

 // C++11

 A.for_each( [](arma::mat::elem_type& val) { std::cout << val << std::endl; } );

关于C++ Armadillo : double for loop using iterators,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34644239/

相关文章:

c++ - CLion 禁用 C++98 模式以支持 C++11

c++ - 为什么我不能在 Armadillo 中得到这个对称正定矩阵的平方根?

c++ - Armadillo:高效的 RAM 稀疏批量插入

opencv - cv::Mat 和 arma::mat 之间的转换

c++ - 打印 vector 的 vector

c++ - 为什么我的程序不断循环?

c++ - 将 Armadillo C++ 库导入 Xcode

c++ - 在 C++ 中返回多个矩阵( Armadillo 库)

c++ - MSVC 常量枚举类型

c++ - 在我的模板类示例中,即使我没有定义 add 方法,它也会添加 take "segmentation fault (core dumped)"错误