Home > Mobile >  Why vector comparision result shows error when not put in parenthesis?
Why vector comparision result shows error when not put in parenthesis?

Time:01-07

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;
}

CodePudding user response:

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.

CodePudding user response:

This requires you to learn operator precedence. And back to what your issue with, why it works with (). The reason is that according to operator precedence the operation within () will be evaluated first.

  • Related