列表迭代崩溃 R

List iteration crashes R

我想在 Rcpp 中进行列表迭代,但此代码使 R 崩溃:

Rcpp::cppFunction('List foo(List bc) {

              for (List::iterator i = bc.begin(); i != bc.end(); ++i) i[0] = i[1];

              return(bc);

            }'
)

如果我们采取以下foo(list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))),R 将崩溃。上面的例子只是一个虚拟的 - 在每个子列表中用第二个元素替换第一个元素(例如,我们应该得到 c(2, 2, 3, 4) for a 和 for b c(3, 3 , 2, 1)).

有人能帮忙吗?我对 R 和 Rcpp 都很陌生,只是浏览文献,但不知道为什么迭代器不起作用。

问题出在 i[0]i[1] 上。迭代器有点像指针,您需要先实例化它们。这是您的代码的一个变体:

代码

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List foo(Rcpp::List bc) {
  for (Rcpp::List::iterator i = bc.begin(); i != bc.end(); ++i) {
    SEXP a = *i;
    Rcpp::print(a);
  }

  return(bc);
}

/*** R
ll <- list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))
foo(ll)
*/

输出

edd@rob:~/git/Whosebug/60291024(master)$ Rscript -e 'Rcpp::sourceCpp("question.cpp")'

R> ll <- list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))

R> foo(ll)
[1] 1 2 3 4
[1] 4 3 2 1
$a
[1] 1 2 3 4

$b
[1] 4 3 2 1

edd@rob:~/git/Whosebug/60291024(master)$