How to print vector's data

后端 未结 3 2055
不知归路
不知归路 2020-12-22 03:44

I\'ve searched a lot over the internet, and couldent find simple examples to print vector\'s data..

I tried to print it like an array, though it didnt worked...

3条回答
  •  北海茫月
    2020-12-22 04:06

    I found the best way to print a vector is to use some kind of wrapper:

    Let's start off with:

    template< typename T >
    class ConstVecFormat
    {
       private:
          std::vector const& vec_;
          const std::string prefix_, delim_, suffix_;
    
       public:
          explicit ConstVecFormat( std::vector const& vec, prefix="", delim=",", suffix="" ) :
              vec_(vec), prefix_(prefix), delim_(delim), suffix_(suffix_)
          {
          }
    
          std::ostream& print( std::ostream& os ) const
          {
             typename std::vector::const_iterator iter = vec_.begin(), end=vec_.end();
             os << prefix_;
             if( iter != end )
                  os << *iter;
             else 
               while( ++iter != end )
               {
                 os << delim_ << *iter;
               }
    
             os << suffix_;
             return os;
          }
     };
    
     template< typename T >
     std::ostream & operator<<( std::ostream & os, ConstVecFormat const& format )
     {
         return format.print( os );
     }
    

    This is heading towards being a duplicate of a previous topic where we enhanced this template a lot to produce one more generic for printing collections.

提交回复
热议问题