[英]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.