Ever wanted to print a std::vector to stdout/stderr, but been met with a missing operator compile error? It's annoying and simple to fix. Just define operator<< in a header file. Here's a short example:
#include <iostream>
#include <vector>
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& v) {
out << "[";
for(typename std::vector<T>::const_iterator it = v.begin(); it != v.end(); ++it) {
out << *it;if(it != v.end()-1) out << ", ";
}
out << "]";
return out;
}
int main() {
std::vector<int> v;
v.push_back(1);
std::cerr << v << std::endl;
}
Follow-up: In non-trivial programs, where you (should) use namespaces, you might need to drop operator<< in namespace std due to argument dependent lookup (http://en.wikipedia.org/wiki/Argument-dependent_name_lookup). Thanks to Kenneth Heafield for this one.
ReplyDelete