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
}
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
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?
I like Boost Spirit Karma for these kind of small formatting/generator tasks.
Direct approach
If you don't mind trailing tabs on each line, here's
Live On Coliru
Prints
Using
multi_array
viewYou get much more flexibility when you use the
const_multi_array_ref
adapter as a "view" on your raw storage:Live On Coliru
This results in the same, but doesn't have the trailing tabs on each line:
Update Make it more readable and less error prone with a helper function:
So it becomes just
Live On Coliru
Which is very elegant, in my opinion