Overloading ostream for vector class

Dec 6, 2013 at 5:46pm
Currently making a programme which allows the user to create vectors of size n, input the values and perform operations on them, such as addition, scalar multiplication.

I have no problems creating the vector and inputting the values, but am struggling to create a suitable operator overloading function for <<.

My class is named T.
My class has an set and get function. The set function inputs each element of the vector and uses the push.back to assign the values. The get function retrieves the vector from private.

Currently I have:

 
ostream& operator<<(ostream&, vector<T>&);


1
2
3
4
5
6
7
8
9
ostream& operator << (ostream& os, vector<T>& P)
   {
   for (int i=0; i = P.size() ; i++)
        {
            os << P.getT()[i] << "," ;
        }

   return os;
   }


Any idea why this code isnt working?
Dec 6, 2013 at 6:01pm
i = P.size() should be i < P.size()
Dec 6, 2013 at 6:21pm
Ahhh, silly me.

However, this still gives the error:


'class T' has no member named 'size'

=== Build finished: 1 errors, 0 warnings ===


Dec 6, 2013 at 6:55pm
Something like this, maybe...
1
2
3
4
5
6
7
8
9
10
11
12
template <class T>
ostream & operator << (ostream& os, const vector<T>& P)
{
    for (unsigned int i=0; i < P.size() ; i++)
    {
        if (i > 0)
            os << ',';
        os << P[i];
    }
  
    return os;
}


Your class may need a friend function to allow individual instances to use ostream <<
Last edited on Dec 6, 2013 at 6:58pm
Topic archived. No new replies allowed.