[英]Rcpp produces different output when not printing blank line
我正在嘗試編寫一個函數,該函數接受一個由 0 和 1 組成的向量(輸入),並返回一個等於第一個向量的向量,但是如果任何先前的元素為 0(res),則每個元素都被 0 覆蓋。 第一個元素默認為 1。 為此,對於每個 i,我返回輸入向量的第 i 個元素和前一個結果 (prev_res) 中的最小值。
當我運行我的函數時,我得到了錯誤的輸出(正是輸入),但是當我調用std::cout
來打印一個空行時,我得到了預期的結果。 這看起來很奇怪!
我附上了下面的代碼。
library(Rcpp)
cppFunction(
'NumericVector any_zeroes_previously(IntegerVector input) {
// ** input is a vector of 0 and 1, indicating if timeperiod_num==lag_timeperiod_num+1 **
NumericVector res = NumericVector(input.length());
for (int i=0; i<input.length(); i++) {
int prev_res;
if (i==0) {
// first row of new group
res[i] = 1;
prev_res = 1;
} else {
// 2nd row of group onwards
res[i] = std::min(input[i], prev_res);
prev_res = res[i];
// ** when next line is commented out, produces incorrect result **
std::cout << "";
}
}
return res;
}')
test = c(1,1,0,1,0,0)
# expected result: 1 1 0 0 0 0
# result with print: 1 1 0 0 0 0
# result without print: 1 1 0 1 0 0
any_zeroes_previously(test)
您正在使用變量prev_res
未初始化,這是未定義的行為,可以是任何東西。
for 循環的每次迭代都會重新聲明prev_res
,如果i != 0
,則取input[i]
和prev_res
(任何值)的最小值。 一個簡單的解決方法是在 for 循環之外使用prev_res
:
cppFunction(
'NumericVector any_zeroes_previously(IntegerVector input) {
// ** input is a vector of 0 and 1, indicating if timeperiod_num==lag_timeperiod_num+1 **
NumericVector res = NumericVector(input.length());
int prev_res;
for (int i=0; i<input.length(); i++) {
if (i==0) {
// first row of new group
res[i] = 1;
prev_res = 1;
} else {
// 2nd row of group onwards
res[i] = std::min(input[i], prev_res);
prev_res = res[i];
// ** when next line is commented out, produces incorrect result **
std::cout << "";
}
}
return res;
}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.