Skip to content

Instantly share code, notes, and snippets.

@yairchu
Last active May 3, 2021 11:53
Show Gist options
  • Save yairchu/85e6821fd19379fb78c86f5f2b28a4ac to your computer and use it in GitHub Desktop.
Save yairchu/85e6821fd19379fb78c86f5f2b28a4ac to your computer and use it in GitHub Desktop.
operator<< for STL types
#include <iostream>
#include <map>
#include <vector>
// Adding forward declarations would make this compile
// template <typename K, typename V>
// std::ostream& operator<< (std::ostream&, const std::map<K, V>&);
// template <typename T>
// std::ostream& operator<< (std::ostream&, const std::vector<T>&);
// Implementation
template <typename K, typename V>
std::ostream& operator<< (std::ostream& o, const std::map<K, V>& map)
{
const char* sep = "{";
for (const auto& x : map)
{
o << sep << "{" << x.first << ", " << x.second << "}";
sep = ", ";
}
return o << "}";
}
template <typename T>
std::ostream& operator<< (std::ostream& o, const std::vector<T>& vec)
{
const char* sep = "{";
for (const auto& x : vec)
{
o << sep << x;
sep = ", ";
}
return o << "}";
}
// Usage
int main()
{
std::map<int, std::vector<int>> t = {{1, {2, 3}}, {4, {5}}};
std::cout << t << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment