将Boost ublas矩阵写入文本文件 [英] Writing a Boost ublas matrix to a text file
问题描述
我有一个Boost ublas矩阵,我想将其内容打印到一个文本文件中.我有以下实现,并且可以正常工作.
I have a Boost ublas matrix, and I want to print its contents to a text file. I have the following implementation, and it works.
#include <iostream>
using namespace std;
#include "boost\numeric\ublas\matrix.hpp"
typedef boost::numeric::ublas::matrix<float> matrix;
#include <algorithm>
#include <iterator>
#include <fstream>
int main()
{
fill(m1.begin2(), m1.begin2() + 400 * 500, 3.3);
ofstream dat("file.txt");
for (auto i = 0; i < 400 ; i++) {
for (auto j = 0; j < 500; j++) {
dat << m1(i, j) << "\t"; // Must seperate with Tab
}
dat << endl; // Must write on New line
}
我想编写此代码而不使用嵌套的for循环.我尝试了如下的ostreambuf_iterator API
I want to write this code without using the nested for loops. I tried the ostreambuf_iterator API as follows
copy(m1.begin2(), m1.begin2() + 500 * 400, ostream_iterator<float>(dat, "\n")); // Can only new line everything
但是,正如您所看到的,连续的元素写在换行上,而且我无法像使用嵌套的for循环那样实现排序的类型.有没有一种方法可以使用STL算法在嵌套内部进行操作?
However, as you can see, successive elements were written on new line, and I was not able to achieve the type of sequencing as I did with nested for loop. Is there a way to do what I did inside the nested for using an STL algorithm?
推荐答案
我喜欢Boost Spirit Karma来完成这类小型格式化/生成器任务.
I like Boost Spirit Karma for these kind of small formatting/generator tasks.
如果您不介意每行的尾随制表符,则为
If you don't mind trailing tabs on each line, here's
matrix m1(4, 5);
std::fill(m1.data().begin(), m1.data().end(), 1);
using namespace boost::spirit::karma;
std::ofstream("file.txt") << format_delimited(columns(m1.size2()) [auto_], '\t', m1.data()) << "\n";
打印
1.0 → 1.0 → 1.0 → 1.0 → 1.0 →
1.0 → 1.0 → 1.0 → 1.0 → 1.0 →
1.0 → 1.0 → 1.0 → 1.0 → 1.0 →
1.0 → 1.0 → 1.0 → 1.0 → 1.0 →
使用multi_array
视图
将const_multi_array_ref
适配器用作原始存储上的视图"时,您将获得更大的灵活性:
Using multi_array
view
You get much more flexibility when you use the const_multi_array_ref
adapter as a "view" on your raw storage:
std::ofstream("file.txt") << format(auto_ % '\t' % eol,
boost::const_multi_array_ref<float, 2>(&*m1.data().begin(), boost::extents[4][5]));
结果相同,但每行上都没有尾随制表符:
This results in the same, but doesn't have the trailing tabs on each line:
1.0 → 1.0 → 1.0 → 1.0 → 1.0
1.0 → 1.0 → 1.0 → 1.0 → 1.0
1.0 → 1.0 → 1.0 → 1.0 → 1.0
1.0 → 1.0 → 1.0 → 1.0 → 1.0
更新,借助辅助功能,使其更具可读性,并且减少了出错的可能性:
Update Make it more readable and less error prone with a helper function:
template <typename T> boost::const_multi_array_ref<T, 2> make_view(boost::numeric::ublas::matrix<T> const& m) {
return boost::const_multi_array_ref<T,2> (
&*m.data().begin(),
boost::extents[m.size1()][m.size2()]
);
}
所以就变成了
std::cout << format(auto_ % '\t' % eol, make_view(m1)) << "\n";
在我看来,非常优雅
注意当然,这些假设采用行为主的布局.
Note Of course these assume row-major layout.
这篇关于将Boost ublas矩阵写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!