I'm overloading operator << to output my container separated by space:
std::ostream& operator<< (std::ostream &os, const MyContainer &v)
{
os << "[";
for (const auto &i : v) {
os << i << " ";
}
os << "\b]"; // <--
return os;
}
MyContainer c{1,2,3};
std::cout<<c<<std::endl;
I'm using '\\b' to avoid the extra space at the end of the list, it works fine with above code.
But it might not be a good idea, does '\\b' work well with other types of ostream
? Any other idea to output data like this?
But it might not be a good idea, does
'\\b'
work well with other types ofostream
?
You are absolutely right about this not being a good idea: '\\b'
works fine in console mode, but it does not play well with other streams, such as files.
A better approach is to not output the extra space in the first place:
std::ostream& operator<< (std::ostream &os, const MyContainer &v)
{
os << "[";
auto first = true;
for (const auto &i : v) {
if (!first) {
os << " ";
} else {
first = false;
}
os << i;
}
os << "]";
return os;
}
A simple pragmatic solution is to just add a space before the range loop:
std::ostream& operator<< (std::ostream &os, const MyContainer &v)
{
os << "[ "; // <--
for (const auto &i : v) {
os << i << " ";
}
os << "]";
return os;
}
MyContainer c{1,2,3};
std::cout<<c<<std::endl;
The result is a slightly different output, but still achieves the presumed goal of visually pleasing symmetrical formatting: instead of [1 2 3]
you get [ 1 2 3 ]
. Empty lists will print as [ ]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.