Yahor Vaziyanau
Yahor Vaziyanau

Reputation: 365

How to overload ostream (<<) for vector (to print all collection from vector)

I don't know how to print all information from vector and how to call overload ostream ? Can u help ???

template<class T>
class MainVector {
...
...
};
ostream &operator<<(ostream &os, const MainVector<T> &vect) {
/*
 Code here down
*/
}

Upvotes: 0

Views: 3009

Answers (2)

user4578093
user4578093

Reputation: 229

template<typename T>
std::ostream& operator<<(std::ostream& Os, MainVector<T>& MVec){
  // You did not mention what the structure of MainVector was, so I will assume wildly
  Os << "[ ";
  for (int i = 0; i < MVec.size(); i++)
    Os << MVec[i] << ", ";
  Os << "\b\b ]"; // \b behaves like a backspace, usually
  // Assuming that your class is similar to std::vector, this code will loop 
  // through its elements and print them one by one

  // Note that Os behaves like std::cout,
  // If you have any element that can be output with cout, you can use the same syntax here
  // For instance, to output an integer in MainVector:
  // Os << MainVector.AnInteger;

  return Os;
  // This allows the operator to be chained like: std::cout << 1 << 2 << 3 << '\n';
} // Output is as follows

// [ Element1, Element2, /*etc.*/, ElementN ]

This function should be called any use of the << operator on std::cout or another stream with an instance of MainVector, e.g.

std::cout << AnInstanceOfMainVector << '\n';

In future please include the basic structure of your class

Upvotes: 0

Daniel Strul
Daniel Strul

Reputation: 1528

Below is a typical template you could use for formatted output of vectors:

template<class T>
ostream& operator<<(ostream& stream, const std::vector<T>& values)
{
    stream << "[ ";
    copy( begin(values), end(values), ostream_iterator<T>(stream, " ") );
    stream << ']';
    return stream;
}

Upvotes: 4

Related Questions