gpt4 book ai didi

c++ - Rcpp 在不打印空行时产生不同的输出

转载 作者:行者123 更新时间:2023-12-03 06:53:37 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,该函数接受一个由 0 和 1 组成的 vector (输入),并返回一个等于第一个 vector 的 vector ,但如果任何前一个元素为 0 (res),则每个元素都被 0 覆盖。第一个元素默认为 1。为此,对于每个 i,我返回输入 vector 的第 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(任何值)。一个简单的解决方法是将 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;
}')

关于c++ - Rcpp 在不打印空行时产生不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64217035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com