The C++ template for Printing the Vector/List/Set/Map by Overriding the cout Operator?


The cout is a very easy but powerful techique to debug (for example, submiting code to Online Judge). However, by default, the C++ cout does not accept the vector or list. But we can easily override the << operator:

1
2
3
4
5
6
template <typename T>
ostream& operator <<(ostream& out, const vector<T>& a) {
  out << "["; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
  return out;
}
template <typename T>
ostream& operator <<(ostream& out, const vector<T>& a) {
  out << "["; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
  return out;
}

The above template operator override supports generic type T and you can change the vector to some other container type, such as list, set or even map.

With the above, you then can do this:

1
2
vector<int> data({1, 2, 3});
cout << data << endl; // this prints [1, 2, 3]
vector<int> data({1, 2, 3});
cout << data << endl; // this prints [1, 2, 3]

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
198 words
Last Post: Design a Rate Limiter in Python
Next Post: A Concise Python Function to Check Subsequence using Iterator

The Permanent URL is: The C++ template for Printing the Vector/List/Set/Map by Overriding the cout Operator?

Leave a Reply