使用迭代器遍历boost :: ublas矩阵 [英] Traversing a boost::ublas matrix using iterators

查看:127
本文介绍了使用迭代器遍历boost :: ublas矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想从头到尾遍历每个元素.但是,我看到没有一个用于boost矩阵的迭代器,而是有两个迭代器,而且我还无法弄清楚如何使它们起作用,以便遍历整个矩阵

I simply want to traverse a matrix from start to finish touching upon every element. However, I see that there is no one iterator for boost matrix, rather there are two iterators, and I haven't been able to figure out how to make them work so that you can traverse the entire matrix

    typedef boost::numeric::ublas::matrix<float> matrix;

    matrix m1(3, 7);

    for (auto i = 0; i < m1.size1(); i++)
    {
        for (auto j = 0; j < m1.size2(); j++)
        {
            m1(i, j) = i + 1 + 0.1*j;
        }
    }

    for (auto itr1 = m1.begin1(); itr1!= m1.end1(); ++itr1)
    { 
        for (auto itr2 = m1.begin2(); itr2 != m1.end2(); itr2++)
        {
            //std::cout << *itr2  << " ";
            //std::cout << *itr1  << " ";
        }
    }

我的这段代码使用itr1仅打印矩阵的row1,使用itr2只打印矩阵的column1.可以做什么来代替访问所有行和列呢?

This code of mine, prints only row1 of matrix using itr1 and only column1 of the matrix using itr2. What can be done to instead access all rows and columns?

推荐答案

要遍历矩阵,应从iterator1提取iterator2,如下所示:

To iterate over the matrix, iterator2 should be fetched from iterator1, like this:

for(auto itr2 = itr1.begin(); itr2 != itr1.end(); itr2++)

完整代码:

#include <stdlib.h>
#include <boost/numeric/ublas/matrix.hpp>

using namespace boost::numeric::ublas;
using namespace std;

int main(int argc, char* argv[]) {

  typedef boost::numeric::ublas::matrix<float> matrix;

  matrix m1(3, 7);
  for (auto i = 0; i < m1.size1(); i++) {
    for (auto j = 0; j < m1.size2(); j++) {
      m1(i, j) = i + 1 + 0.1*j;
    }
  }

  for(matrix::iterator1 it1 = m1.begin1(); it1 != m1.end1(); ++it1) {
    for(matrix::iterator2 it2 = it1.begin(); it2 !=it1.end(); ++it2) {
      std::cout << "(" << it2.index1() << "," << it2.index2() << ") = " << *it2 << endl;
    }
    cout << endl;
  }

  return EXIT_SUCCESS;
}

输出:

(0,0) = 1
(0,1) = 1.1
(0,2) = 1.2
(0,3) = 1.3
...

这篇关于使用迭代器遍历boost :: ublas矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆