0

In the following code, I was getting lot of errors. When I use cout << (v1 > v2) << endl instead, all the errors disappeared and I get the correct output. Why is this so? Here is the first part of the error I got (there were lot of errors but if needed I will post all of them):

abc.cpp: In function 'int main()':

abc.cpp:18:10: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'std::vector<int>') 

and me code is:

/* #include <bits/stdc++.h> */

#include <iostream>
#include <algorithm>
#include <vector>

//using namespace std;
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::sort;

int main(void)
{
    vector <int> v1 = {1, 2, 3};
    vector <int> v2 = {1, 2, 5};
    cout << v1 > v2 << endl;

    // free variables
    return 0;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
RubyShanks
  • 138
  • 8
  • 5
    Are you familiar with [C++ operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence) rules? Hint: `<<` comes before `<`, so you're actually asking for `(cout << v1) > (v2 << endl)` – tadman Jan 06 '23 at 18:46
  • It is about [operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence). Without parenthesis you get `(cout << v1) > (v2 << endl)` – BoP Jan 06 '23 at 18:48
  • This is because `<<` was originally only left-shift, and `1 << 2 > 1 << 3` should be `(1 << 2) > (1 << 3)`. This had some unfortunate effect when it was adopted as the stream insertion operator. – molbdnilo Jan 06 '23 at 18:50
  • 1
    Actually I'm new to C++ and used to use C before this.. Never faced this problem with C so I missed it here:/ – RubyShanks Jan 06 '23 at 18:50
  • [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Jesper Juhl Jan 06 '23 at 19:31

1 Answers1

6

The reason you need the paratheses is because of operator precedence. > has lower precedence than << so

cout << v1 > v2 << endl;

is actually

(cout << v1) > (v2 << endl);

which is why you get an error.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402