AmitM9S6
AmitM9S6

Reputation: 131

How to print vector's data

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

Here's what I tried :

using namespace std ;
.....
const int MAX = 255 ;

vector <string> testersName[MAX];
cout << testersName[i] << endl;

The error is only in the cout line, the first line is getting complied and everything goes well..

I got data inside testersName, though Im getting this error :

"Error 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::vector<_Ty>' (or there is no acceptable conversion)"

Upvotes: 1

Views: 7223

Answers (3)

CashCow
CashCow

Reputation: 31445

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.

Upvotes: 0

alestanis
alestanis

Reputation: 21863

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)

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

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

Upvotes: 5

Related Questions