I use about 6 different C++ containers. I started writing print functions to output the container contents. Is this necessary? I would think this is part of the C++ library?<
It's not part of the library, but its easy to write with the tools provided:
C c; // Where C is a container type
std::copy(
c.begin(), c.end()
, std::ostream_iterator< C::value_type >( cout, " " )
);
For containers whose element is a pair
(like map
and I'd believe unordered_map
) you'd need a custom Output Iterator to print the pair
with the comma and brackets.
What about:
#include <iostream>
#include <map>
#include <algorithm>
template <typename K, typename V>
std::ostream& operator<<(std::ostream& os, const std::pair<K,V>& p)
{
return os << "[" << p.first << ", " << p.second << "]";
}
template <typename Container>
std::ostream& operator<<(std::ostream& os, const Container& c)
{
std::copy(c.begin(), c.end(),
std::ostream_iterator<typename Container::value_type>(os, " "));
return os;
}
You might also be charmed about Boost Spirit Karma:
#include <boost/spirit/include/karma.hpp>
using boost::spirit::karma::format;
using boost::spirit::karma::auto_;
int main()
{
std::vector<int> ints(1000);
std::map<std::string, int> pairs();
// ...
std::cout << format(auto_ % " ", ints) << std::endl;
std::cout << format(('[' << auto_ << ',' << ']') % " ", pairs) << std::endl;
}
The code you give in your question has a hint as to why it is not part of the standard library. Your code uses square brackets and a comma with no spaces to show the pairs in the map. Other people may want it formatted differently so the options the standards committee had were:
They went with option three knowing that libraries would be developed that meet people's specific needs.