gpt4 book ai didi

c++ - Boost矩阵的iterator1和iterator2是什么,如何使用?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:02:22 27 4
gpt4 key购买 nike

我正在寻找一种使用迭代器迭代 Boost 矩阵元素的方法。 Documentation报告返回迭代器 1 和迭代器 2 的矩阵方法:

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 是如何使用的?

最佳答案

事实证明,这两个迭代器允许根据需要按行或按列迭代矩阵。 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

关于c++ - Boost矩阵的iterator1和iterator2是什么,如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260574/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com