简体   繁体   中英

"No match for operator>>" but I don't understand why. Could you explain me, please?

I have got the following code:

#include <iostream>
#include <vector>

using namespace std;

vector<int> Reversed(const vector<int>& v){
    
    //vector<int> v;  //[Error] declaration of 'std::vector<int> v' shadows a parameter
    int z; vector<int> copy; vector<int> working;
    working = v;
    z = working.size();
    int i;
    for (i = 0; i<=z; i++){
        working[i] = working[z];
        copy.push_back(working[i]);
    }
    return copy;
}

int main() {
    
    vector<int> v;
    cin >> v;  /*[Error] no match for 'operator>>' (operand types are 'std::istream' 
                {aka 'std::basic_istream<char>'} and 'std::vector<int>')*/
    cout << Reversed(v);
    return 0;
}

Please, explain to me why I am getting this error on line 18:

no match for operator >>`

Ps: const & i is a prerequisite task, I cannot change it. I just need an upside-down copy of this vector.

It looks like you are asking the user to enter a list of numbers. std::cin (or just cin , since you've got use namespace std; ) doesn't know how to receive a list of integers and turn that into a vector<int> for you.

If you want to receive a vector from user input, I would suggest you ask the user for a list of numbers, something like:

// replace VECTOR_LENGTH
for (int i = 0; i < VECTOR_LENGTH; i++) {
  int num;
  cin >> num;
  v.push_back(num);
}

You are trying to read the whole vector in one go when you do this cin >> v; . You probably want to read one element at a time, like:

#include <iostream>
#include <vector>

using namespace std;

int main(void)
{
   // read five integers from stdin
  const int n = 5;
  vector<int> v(n);
  for(int i = 0; i < n; ++i)
    cin >> v[i];
  for(int i = 0; i < n; ++i)
    cout << v[i] << "\n";
  return 0;
}

Output:

0
1
2
3
4

Or use std::vector::push_back as in @ajm answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM