![](/img/trans.png)
[英]error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
[英]error: invalid initialization of non-const reference of type int& from an rvalue of type int
在下面的代碼中,當我將idx
和sum
作為參考時,它顯示給定的錯誤。 如果我在沒有參考的情況下使用idx
和sum
,它工作正常。 為什么?
void func(int &idx, int &sum, vector<int> &arr, int N, vector<int> &res)
{
if(idx == N)
{
res.push_back(sum);
return;
}
// pick the element
func(idx + 1, sum+arr[idx], arr, N, res);
// not pick the element
func(idx + 1, sum, arr, N, res);
}
vector<int> subsetSums(vector<int> arr, int N)
{
// Write Your Code here
int idx = 0;
int sum = 0;
vector<int> res;
func(idx, sum, arr, N, res);
sort(res.begin(), res.end());
return res;
}
idx + 1
是臨時的,它沒有地址,因此不能綁定到引用。 sum+arr[idx]
也是如此。
將const
用於僅輸入參數可能是個好主意。 因為const int&
可以綁定到臨時對象。 雖然沒有理由通過常量引用來傳遞整數類型,但通過值傳遞是可以的。
您遞歸調用func
並將idx + 1
作為第一個參數傳遞,但idx + 1
不能是左值引用,只能是右值,因為它是一個臨時值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.