采取以下代码,出于演示目的,采用普通的IntegerVector
作为输入。指某东西的用途std::ostringstream
相当简单,在尝试执行像您这样的操作时会派上用场。
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
String concat(IntegerVector x) {
// convert intput to 'CharacterVector'
int nChar = x.size();
CharacterVector y = as<CharacterVector>(x);
// initialize string output stream
std::ostringstream ossOut;
// concatenate input
for (int i = 0; i < nChar; i++)
ossOut << y[i];
return ossOut.str();
}
现在,使用以下命令将函数加载到 R 中sourceCpp
并从内部调用它*apply
loop.
## source c++ function
library(Rcpp)
sourceCpp("~/work/programming/concat.cpp")
## test run
lst <- list(c(0, 1, 0, 0, 0, 0),
c(0, 0, 0, 0, 0, 1),
c(0, 1, 0, 0, 0, 0),
c(0, 0, 0, 1, 0, 0))
lapply(lst, concat)
[[1]]
[1] "010000"
[[2]]
[1] "000001"
[[3]]
[1] "010000"
[[4]]
[1] "000100"