Necessity of writing print functions for containers?

后端 未结 3 736
刺人心
刺人心 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:27

    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.

    0 讨论(0)
  • 2021-01-26 14:31

    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;
    }
    
    0 讨论(0)
  • 2021-01-26 14:35

    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:

    1. Provide a lot of formatting options.
    2. Provide no formatting options and make everyone who doesn't like their formatting roll their own.
    3. Do nothing and make everyone roll their own

    They went with option three knowing that libraries would be developed that meet people's specific needs.

    0 讨论(0)
提交回复
热议问题