我们首先生成一些列表,其中包含列表:
lappend <- function(lst, ...){
lst <- c(lst, list(...))
return(lst)
}
scalarList <- list()
vectorList <- list()
MatrixList <- list()
for (i in 1:3){
scalarList <- lappend(scalarList,i)
vectorList <- lappend(vectorList,0:i)
MatrixList <- lappend(MatrixList, diag(i + 1))
}
myRList <- list(scalarList = scalarList, vectorList = vectorList,
MatrixList = MatrixList)
现在我们的myRList已经准备好了,我想用C ++编写一个函数,如下所示:
1)输入:1)myRList,2)从1到3的ID
2)输出:该函数应分别打印与输入id对应的标量,向量和矩阵。
3)可能有很多方法可以编写此函数。我特别想读入列表,将其分配给相应的arma对象,然后打印出来。原因是我写了这个简化的示例,以向你们学习如何提取Rcpp中另一个列表中的列表元素并将其分配给arma对象。
这是我的C ++代码:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
double myListExtractor( Rcpp::List aList_In_R, int id){
int myScalar = Rcpp::as<double>(aList_In_R["scalarList"][id]); //? what to do ?
arma::vec myVector = Rcpp::as<arma::vec>(aList_In_R["vectorList"[id]]); //???
arma::mat myMatrix = Rcpp::as<arma::mat>(aList_In_R["MatrixList"[id]]); //???
// If I manage to do the three assignments above, then printing is easy:
Rcpp::Rcout << "myScalar = " << myScalar << std::endl;
Rcpp::Rcout << "myVector = " << myVector << std::endl;
Rcpp::Rcout << "myMatrix = " << myMatrix << std::endl;
return 1; // we don't care about the return for now
}
同样,我100%同意无需将它们分配给arma对象然后进行打印。在我自己的代码中,我对arma对象进行了大量的代数运算,这就是我强调此作业以学习如何修复代码/的原因。
预先非常感谢您的帮助。另外,我花了3个小时浏览网络,但没有找到任何答案。
因为List
对象对它们所包含的对象的类型一无所知,所以您必须as
在子设置的每个级别。例如:
int myScalar = Rcpp::as<double>( Rcpp::as<Rcpp::List>(aList_In_R["scalarList"])[id] );
这样,我们可以向编译器发出信号,表明我们要从aList_In_R
中提取的插槽是List
,并且对List
s拥有的所有方法都应在此处应用。这很丑陋,但是使用静态类型语言对动态类型语言中使用的对象进行操作时,这是不幸的结果。
有一些将模板化列表容器放入Rcpp
其中的工作可能有助于解决这种情况。例如,List
您可能有一个而不是拥有一个ListOf< List >
子集运算符的子集运算符,它将“知道”子集运算符应List
在子集设置后返回,这可能会更好一些。也许它可以深入到ListOf< ListOf< double > >
,等等。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句