Rcpp在不打印空行时会产生不同的输出结果

3
我正在尝试编写一个函数,该函数接受一个由0和1组成的向量(输入),并返回一个等于第一个向量的向量,但如果任何先前的元素为0,则将每个元素覆盖为0 (结果)。默认情况下,第一个元素为1。为了实现这一点,对于每个i,我返回输入向量的第ith元素和前一个结果(prev_res)的最小值。
当我运行我的函数时,我得到了错误的输出(恰好是输入),但是当我包含调用以打印空行时,我得到了预期的结果。这似乎很奇怪!
以下是附加的代码:
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)
1个回答

4

您正在使用未初始化的变量prev_res,这是未定义的行为,可以是任何值。

您的for循环的每次迭代都会重新声明prev_res,如果i!= 0,则会取input [i]prev_res(任何值)中的最小值。一个简单的解决方法是将 prev_res 移到for循环之外:

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;
  }')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接