Skip to content

Instantly share code, notes, and snippets.

@zorchp
Last active May 16, 2023 09:25
Show Gist options
  • Save zorchp/10059e38bbf06f19fb09c0e1a2fb4d86 to your computer and use it in GitHub Desktop.
Save zorchp/10059e38bbf06f19fb09c0e1a2fb4d86 to your computer and use it in GitHub Desktop.
C++ print 1d 2d vector and other containers by template and operator<< overload
// all container which support range-for-loop
template <typename T, template <typename> class Container>
ostream &operator<<(ostream &os, const Container<T>& v) {
for (auto i : v) os << i << " ";
return os << endl;
}
// ========================== vector ==============================
template <typename T>
ostream &operator<<(ostream &os, const vector<T>& v) {
for (auto i : v) os << i << " ";
return os << endl;
}
template <typename T>
ostream &operator<<(ostream &os, const vector<vector<T>>& v) {
for (auto i : v) os << i;
return os << endl;
}
// ====================== list =====================================
template <typename T>
ostream &operator<<(ostream &os, const list<T>& v) {
for (auto i : v) os << i << " ";
return os << endl;
}
// =========================== deque ===========================
template <typename T>
ostream &operator<<(ostream &os, const deque<T>& v) {
for (auto it = v.begin(); it != v.end(); ++it) os << *it << " ";
return os << endl;
}
// ========================== queue stack ==========================
template <typename T>
ostream &operator<<(ostream &os, queue<T> st) { // pass by value
for (; !st.empty(); st.pop()) os << st.front() << " ";
return os << endl;
}
template <typename T>
ostream &operator<<(ostream &os, stack<T> st) { // pass by value
for (; !st.empty(); st.pop()) os << st.top() << " ";
return os << endl;
}
// ========================= priority_queue ======================
template <typename T>
ostream &operator<<(ostream &os, priority_queue<T> st) { // pass by value
for (; !st.empty(); st.pop()) os << st.top() << " ";
return os << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment