我有以下代码:
#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;
}
请向我解释为什么我在第18行出现此错误:
与运算符>>'不匹配>
P.s。:const & i
是一项先决任务,我无法更改。我只需要此向量的上下副本。
答案 0 :(得分:3)
您似乎在要求用户输入数字列表。 std::cin
(或者只有cin
,因为您已经拥有use namespace std;
)不知道如何接收整数列表并将其转换为vector<int>
。< / p>
如果您想从用户输入中接收向量,建议您向用户询问数字列表,例如:
// replace VECTOR_LENGTH
for (int i = 0; i < VECTOR_LENGTH; i++) {
int num;
cin >> num;
v.push_back(num);
}
答案 1 :(得分:2)
执行此cin >> v;
时,您试图一次性读取整个向量。您可能想一次读取一个元素,例如:
#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;
}
输出:
0
1
2
3
4
或者使用@ {aj3答案中的std::vector::push_back
。