How to print vector's data

后端 未结 3 2041
不知归路
不知归路 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<T> const& vec_;
          const std::string prefix_, delim_, suffix_;
    
       public:
          explicit ConstVecFormat( std::vector<T> const& vec, prefix="", delim=",", suffix="" ) :
              vec_(vec), prefix_(prefix), delim_(delim), suffix_(suffix_)
          {
          }
    
          std::ostream& print( std::ostream& os ) const
          {
             typename std::vector<T>::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<T> 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.

    0 讨论(0)
  • 2020-12-22 04:10

    vector <string> testersName[MAX]; declares an array of vectors, try simply vector <string> testersName(MAX); - this declares a vector with MAX elements.

    0 讨论(0)
  • 2020-12-22 04:10

    You have to iterate over the vector's elements and then brint each one :

    vector <string> testersName;
    // Fill your vector
    for (int i = 0; i < testersName.size(); ++i) {
        cout << testersName[i] << endl;
    }
    

    Moreover, I don't think the line vector <string> testersName[MAX]; does what you think it does. It is not necessary to give a size to the vector because it grows dynamically when you fill it. If you still want to give a size, use parenthesis : (MAX)

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