2

我正在寻找一种使用迭代器迭代 Boost 矩阵元素的方法。文档报告返回 iterator1 和 iterator2 的 Matrix 方法:

iterator1 begin1 () Returns a iterator1 pointing to the beginning of the matrix.
iterator1 end1 ()   Returns a iterator1 pointing to the end of the matrix.
iterator2 begin2 () Returns a iterator2 pointing to the beginning of the matrix.
iterator2 end2 ()   Returns a iterator2 pointing to the end of the matrix.

我尝试遍历它们,并且 iterator1 遍历矩阵的第一列(仅),而 iterator2 遍历第一行(仅)。

这些 iterator1 和 iterator2 是如何使用的?

4

1 回答 1

1

事实证明,这两个迭代器允许根据需要逐行或逐列迭代矩阵。在CuriouslyRecurringThoughts报告的链接上有一个答案,但我也在这里为任何感兴趣的人提供了我的代码的使用示例。下面的程序填充这个整数矩阵

1, 0, 2, 4, 3
4, 6, 5, 2, 1
4, 4, 5, 2, 1
5, 6, 8, 5, 3

然后打印它,首先按行,然后按列。

#include <vector>
#include <iostream>

#include "boost/numeric/ublas/matrix.hpp"
#include "boost/numeric/ublas/io.hpp"

using std::vector;
using boost::numeric::ublas::matrix;
using std::cout, std::endl;


matrix<int> make_matrix(vector<vector<int>> values) {
    auto the_matrix = matrix<int>(values.size(), values[0].size());

    // Copy 'values' into 'the_matrix', one row at a time
    auto iter1 = the_matrix.begin1();
    for (auto values_iter = values.begin(); values_iter != values.end(); ++values_iter, ++iter1)
        std::copy(values_iter->begin(), values_iter->end(), iter1.begin());

    return the_matrix;
}

matrix<int> make_matrix(int size1, int size2, int value) {
    auto the_matrix = matrix<int>(size1, size2);

    for (auto iter1 = the_matrix.begin1(); iter1 != the_matrix.end1(); ++iter1)
        for (auto iter2 = iter1.begin(); iter2 != iter1.end(); ++iter2)
            *iter2 = value;

    return the_matrix;
}

int main() {
    matrix<int> the_matrix = make_matrix({{1, 0, 2, 4, 3},
                                          {4, 6, 5, 2, 1},
                                          {4, 4, 5, 2, 1},
                                          {5, 6, 8, 5, 3}});

    cout << "Print the matrix by rows:" << endl;
    for (auto iter1 = the_matrix.begin1(); iter1 != the_matrix.end1(); ++iter1)
        for (auto iter2 = iter1.begin(); iter2 != iter1.end(); ++iter2)
            cout << *iter2 << " ";

    cout << endl << endl << "Print the matrix by columns:" << endl;
    for (auto iter2 = the_matrix.begin2(); iter2 != the_matrix.end2(); ++iter2)
        for (auto iter1 = iter2.begin(); iter1 != iter2.end(); ++iter1)
            cout << *iter1 << " ";

    cout << endl;
}

这是输出:

Print the matrix by rows:
1 0 2 4 3 4 6 5 2 1 4 4 5 2 1 5 6 8 5 3 

Print the matrix by columns:
1 4 4 5 0 6 4 6 2 5 5 8 4 2 2 5 3 1 1 3 
于 2019-07-30T11:59:13.347 回答