How can I pretty-print a std::vector
? For example, if I construct a std::vector<int>(6, 1)
, what can I run it through to get output like {1 1 1 1 1 1}
in C++? It needs to be generic as the size and value might change, so std::vector<int>(4, 0)
would be {0 0 0 0}
.
#include <vector>
#include <algorithm>
#include <iterator>
template<typename T>
std::ostream & operator<<(std::ostream & os, std::vector<T> vec)
{
os<<"{ ";
std::copy(vec.begin(), vec.end(), std::ostream_iterator<T>(os, " "));
os<<"}";
return os;
}
then you can output your vectors with the normal operator<<
syntax:
std::cout<<yourVector;
you can see this in action here.
But for more flexible solutions have a look at the question linked above.
Edit: if you don't want the two spaces (at the beginning and at the end):
template<typename T>
std::ostream & operator<<(std::ostream & os, std::vector<T> vec)
{
os<<"{";
if(vec.size()!=0)
{
std::copy(vec.begin(), vec.end()-1, std::ostream_iterator<T>(os, " "));
os<<vec.back();
}
os<<"}";
return os;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With