Stream insertion operator of a class template C++ Part3

How can I overload the stream insertion operator of a pair class template?

Tried using friends of classes but didn’t work also tried the below method but didn’t work also

Can someone help me out?
Thanks in advance

A friend function is a good approach. Add the following into your class:

    friend 
    std::ostream& operator<<(std::ostream &out, Pair<K,V> const &p)
    {
        return out << p.key << " " << p.value;
    }

You can try it our here.

1 Like

You should generalize K and V attribute as shown by @MarkoFilipovic. Current (visible) implementation would only support Pair<K: string, V: int>.

Your current class structure does not support pair[key] usage. If you are looking for something like:

cout << pair[key];

then, apart from stream insertion operator you would also need to overload subscript [] operator. Both overloading have been explained in the third part of C++ course.

1 Like

Thanks @MarkoFilipovic, it works perfectly, saw from your code that I omitted the return keyword that’s why the friends of classes method didn’t work initially