Overloading << Operator

I'm studying how to overload the << Operator, as template function at global scope, so I can print elements of the vector by iterating one by one.

it's one of the various methods of printing elements of a vector.

however, i can't get this code to compile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #include <iostream>
#include <vector>

template <typename S> std::ostream& operator<<(std::ostream& os, const std::vector<S>& std::vector)
{
    // Printing all the elements
    // using <<
    for (auto element : std::vector) {
        os << element << " ";
    }
    return os;
}

// Driver Code
int main()
{
    // vector containing integer elements
    std::vector<int> A = { 10, 20, 30, 40, 50, 60 };

    std::cout << A << std::endl;

    return 0;
}



the code's almost word for word, except i didn't write "using namespace std;
it was from here
https://www.geeksforgeeks.org/different-ways-to-print-elements-of-vector/

Could you advise me how to resolve
1) Parameter declarator cannot be qualified
4) Use of class template 'vector' requires template arguments ?
as i try to compile using the online compiler here. the errors i get are

4:88: error: expected ',' or '...'
In function 'std::ostream& operator<<(std::ostream&, const std::vector<S>&)':
8:36: error: missing template arguments before ')' token
In lines 4 and 8 you use the designated type of a variable when you simply want the name of that variable.

In those lines (second occurrence on line 4, only appearance on line 8)
std::vector
just write
v
(say).

The std:: only goes before the name of the non-built-in type or library function. (If you choose to use it.)
Last edited on
thanks, lastchance
Topic archived. No new replies allowed.