![](/img/trans.png)
[英]Could anyone please explain me this function, I am not able to understand this
[英]"No match for operator>>" but I don't understand why. Could you explain me, please?
我有以下代碼:
#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 行收到此錯誤:
不匹配運算符 >>`
Ps: const & i
是前置任務,我無法更改。 我只需要這個向量的顛倒副本。
看起來您要求用戶輸入數字列表。 std::cin
(或只是cin
,因為您有use namespace std;
)不知道如何接收整數列表並將其轉換為vector<int>
。
如果您想從用戶輸入中接收向量,我建議您向用戶詢問數字列表,例如:
// replace VECTOR_LENGTH
for (int i = 0; i < VECTOR_LENGTH; i++) {
int num;
cin >> num;
v.push_back(num);
}
當您執行此操作時,您正試圖一次性讀取整個向量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
或者使用std::vector::push_back
就像在@ajm 答案中一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.