Formated cout of Eigen int vectors with Boost format

I would like to cout the Eigen vectors int, using the boost::formatnumbers to be right justified. So far I have the following code

int main(){ 
vector<Vector3i> foo; Vector3i bar;

bar << -1,-1,0; foo.push_back(bar);
bar <<  0, 0,0; foo.push_back(bar);

boost::format header("%3d");

for (int i = 0; i < 2; ++i)
    cout << header % foo[i].transpose() << endl;

return 0;
}

and the way out is

-1 -1  0
0 0 0

But I want to have the following conclusion

-1 -1  0
 0  0  0

I could achieve the desired result if I changed the format and code inside forwith the following

boost::format header2("%2d %2d %2d");
for (int i = 0; i < 2; ++i) 
    cout << header2 % foo[i](0) % foo[i](1) % foo[i](2) << endl;

But can anyone tell me if there is a more efficient way to do this using boost::format?

+4
source share
1 answer

You can use a workaround:

boost::format header("%+3d"); // Add "+" when is not negative

This will lead to the following conclusion:

-1 -1 +0
+0 +0 +0 

And also you can use Eigen::IOFormatcolors to set the delimiters as follows: (especially useful if elements have a different number of digits)

    boost::format header("%3d");
              //(precision,flags,coeffSeparator,rowSeparator,rowPrefix,rowSuffix)
    IOFormat Fmt(3, 0, "\t", "\n", "", "");
    cout << header % foo[i].transpose().format(Fmt) << endl;

:

-1    -1    0
0     0     0

:

int main(){ 
vector<Vector3i> foo; Vector3i bar;

bar << -1,-1,0; foo.push_back(bar);
bar <<  0, 0,0; foo.push_back(bar);

boost::format header("%+3d");
IOFormat Fmt(3, 0, "\t", "\n", "", "");

for (int i = 0; i < 2; ++i)
    cout << header % foo[i].transpose().format(Fmt) << endl;

return 0;
}

:

-1    -1    +0
+0    +0    +0
0

Source: https://habr.com/ru/post/1689965/


All Articles