I want to print out the contents of a vector in C++, here is what I have:
#include
#include
#include
#include
I think the best way to do this is to just overload operator<<
by adding this function to your program:
#include
using std::vector;
#include
using std::ostream;
template
ostream& operator<< (ostream& out, const vector& v) {
out << "{";
size_t last = v.size() - 1;
for(size_t i = 0; i < v.size(); ++i) {
out << v[i];
if (i != last)
out << ", ";
}
out << "}";
return out;
}
Then you can use the <<
operator on any possible vector, assuming its elements also have ostream& operator<<
defined:
vector s = {"first", "second", "third"};
vector b = {true, false, true, false, false};
vector i = {1, 2, 3, 4};
cout << s << endl;
cout << b << endl;
cout << i << endl;
Outputs:
{first, second, third}
{1, 0, 1, 0, 0}
{1, 2, 3, 4}