Home c++ missing operator "& gt; & gt;" corresponding to these operands (vector, cin)

missing operator “& gt; & gt;” corresponding to these operands (vector, cin)

Author

Date

Category

A simple example, but where is the error, it is difficult for a beginner to understand the pluses …

# include & lt; iostream & gt;
# include & lt; vector & gt;
using namespace std;
int main () {
  vector & lt; int & gt; a;
  cin & gt; & gt; a; \\ there is no operator "& gt; & gt;" corresponding to these operands
  return 0;
}

Answer 1, authority 100%

You cannot read directly into a vector.

int a;
cin & gt; & gt; a;

So – please, but for a vector – you have to rewrite the operator yourself, but I think you just need to read integer values ​​in a loop and add them to the vector using .push_back () .

You can, of course, in other ways, but as a beginner, this will be the easiest.

Something like

int N;
cin & gt; & gt; N; // How many numbers to read
for (int i = 0; i & lt; N; ++ i)
{
  int k;
  cin & gt; & gt; k;
  a.push_back (k);
}

Answer 2, authority 12%

this error occurred because the & gt; & gt; not overloaded for vector.
What is operator overloading and why does it exist in general, read, for example, here

In a nutshell, it works the same way as function overloading (if you know what it is). The only function in your case is the & gt; & gt; operator, and the signature and override, for your case, should look like this.

std :: istream & amp; operator & gt; & gt; (std :: istream & amp; in, std :: vector & lt; int & gt; & amp; a)
{
  int v;
  in & gt; & gt; v;
  a.push_back (v);
  return in;
}

The compiler needs to explain in this way how to read values ​​into a vector using the & gt; & gt; operator.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions