Thursday, March 17, 2011

The missing operator<< for C++ STL's vector

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;
}

1 comment:

  1. 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