How to Print Standard Library Containers
c++17
containers
intermediate
Related: How to Print in C++
C++’s standard library containers do not come with printing capability. In order to print a std::vector
or a std::map
we need to write our own printing function. Here’s example functions for std::vector
and std::map
containing any other types.
#include <iostream> #include <vector> #include <map> using std::ostream; template <typename T> ostream& operator<<(ostream& o, const std::vector<T>& v) { o << "["; if (v.empty()) { o << "]"; return o; } // For every item except the last write "Item, " for (auto it = v.begin(); it != --v.end(); it++) { o << *it << ", "; } // Write out the last item o << v.back() << "]"; return o; } template <typename KeyT, typename ValueT> ostream& operator<<(ostream& o, const std::map<KeyT, ValueT>& m) { o << "{"; if (m.empty()) { o << "}"; return o; } // For every pair except the last write "Key: Value, " for (auto it = m.begin(); it != --m.end(); it++) { const auto& [key, value] = *it; o << key << ": " << value << ", "; } // Write out the last item const auto& [key, value] = *--m.end(); o << key << ": " << value << "}"; return o; } int main() { std::vector vec{1.0f, 2.0f, 3.0f}; std::cout << vec << "\n"; std::map<std::string, float> planetDistances { {"Venus", 0.723f}, {"Earth", 1.0f}, {"Mars", 1.5f}, }; std::cout << planetDistances << "\n"; }
[1, 2, 3] {Earth: 1, Mars: 1.5, Venus: 0.723}