首先,好帖子!不幸的是,您链接的上述资源都与您的问题无关,因为这是由于原型函数中未发现的完全不同的错误所致。为了why原型在调用时返回了一个有效值,这纯粹是运气。
正如 @BenjaminChristoffersen 指出的,代码运行到了一个未定义行为 (UB) https://en.wikipedia.org/wiki/Undefined_behavior由于出界 (OOB) https://en.wikipedia.org/wiki/Bounds_checking发生错误。他的解决方案将有效地“解决”问题。
但是,要在将来自行诊断此问题,请不要使用元素访问器[]
to ()
,它检查您请求的元素是否在范围内。例如是j in 0 to n - 1?
e.g.
if (Vector<RTYPE>::is_na( x( 0 ) )){
// ------------------------^---^
cur_streak = NumericVector::get_na();
} else {
cur_streak = 1;
}
for(int j = i1; j <= i2 ; ++j) {
if( x( j ) == x( j-1 )){
// ^---^-----^-----^
cur_streak += 1;
} else if(Vector<RTYPE>::is_na( x( j ) )){
// --------------------------- ^ ^
cur_streak = NumericVector::get_na();
} else {
cur_streak = 1;
}
}
运行相同的命令然后给出:
streak_run3( c(1,1,1,1),i1=0, i2=3)
Output:
Error in streak_run3(c(1, 1, 1, 1), i1 = 0, i2 = 3) :
Index out of bounds: [index=-1; extent=4].
Input:
streak_run3( as.integer(c(1,1,1,1)),i1=0, i2=3)
Output:
Error in streak_run3(as.integer(c(1, 1, 1, 1)), i1 = 0, i2 = 3) :
Index out of bounds: [index=-1; extent=4].
Input:
streak_run3( as.character(c(1,1,1,1)),i1=0, i2=3)
Output:
Error in streak_run3(as.character(c(1, 1, 1, 1)), i1 = 0, i2 = 3) :
Index out of bounds: [index=-1; extent=4].