Necessity of writing print functions for containers?

后端 未结 3 735
刺人心
刺人心 2021-01-26 13:40

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?<

3条回答
  •  悲&欢浪女
    2021-01-26 14:31

    What about:

    #include 
    #include 
    #include 
    
    template 
        std::ostream& operator<<(std::ostream& os, const std::pair& p)
    {
        return os << "[" << p.first << ", " << p.second << "]";
    }
    
    template 
        std::ostream& operator<<(std::ostream& os, const Container& c)
    {
        std::copy(c.begin(), c.end(), 
            std::ostream_iterator(os, " "));
        return os;
    }
    

    You might also be charmed about Boost Spirit Karma:

    #include 
    
    using boost::spirit::karma::format;
    using boost::spirit::karma::auto_;
    
    int main()
    {
         std::vector ints(1000);
         std::map pairs();
    
         // ...
    
         std::cout << format(auto_ % " ", ints) << std::endl;
         std::cout << format(('[' << auto_ << ',' << ']') % " ", pairs) << std::endl;
    }
    

提交回复
热议问题