简体   繁体   中英

Traversing a boost::ublas matrix using iterators

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  << " ";
        }
    }

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?

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

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

Full code:

#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;
}

Outputs:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM