Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading output stream operator for vector<T>

What is a recommended way to overload the output stream operator? The following can not be done. It is expected that compilation will fail if the operator << is not defined for a type T.

template < class T >
inline std::ostream& operator << (std::ostream& os, const std::vector<T>& v) 
{
    os << "[";
    for (std::vector<T>::const_iterator ii = v.begin(); ii != v.end(); ++ii)
    {
        os << " " << *ii;
    }
    os << " ]";
    return os;
}

EDIT: It does compile, the problem was unrelated and was in the namespace. Thanks for assistance.

like image 269
Leonid Avatar asked Nov 02 '10 12:11

Leonid


People also ask

What is the vector in operator overloading?

What is the vector in operator overloading? Explanation: It is a data type of class. It is defined as public static Vector operator + (Vector a, Vector b).

How do you overload a vector in C++?

Overloaded operators are implemented as functions and can be member functions or global functions. Operator overloading involving vector types is not supported. An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator.

Which operator is overloaded for CIN?

Notes: The relational operators ( == , != , > , < , >= , <= ), + , << , >> are overloaded as non-member functions, where the left operand could be a non- string object (such as C-string, cin , cout ); while = , [] , += are overloaded as member functions where the left operand must be a string object.

How do you overload an operator?

To overload an operator, we use a special operator function. We define the function inside the class or structure whose objects/variables we want the overloaded operator to work with.


1 Answers

This is what you want:

template < class T >
std::ostream& operator << (std::ostream& os, const std::vector<T>& v) 
{
    os << "[";
    for (typename std::vector<T>::const_iterator ii = v.begin(); ii != v.end(); ++ii)
    {
        os << " " << *ii;
    }
    os << "]";
    return os;
}

You forgot the std:: on the first ostream

You put an extra space after [ in os << "[".

and you need typename before std::vector<T>::const_iterator

like image 75
Jason Iverson Avatar answered Nov 15 '22 20:11

Jason Iverson