我有一个 Rcpp 函数,它为我提供了一个包含一些字符串 vector (std::vector) 的列表。
[[1]] [1] "0" "1" "0" "0" "0" "0"
[[2]] [1] "0" "0" "0" "0" "0" "1"
[[3]] [1] "0" "1" "0" "0" "0" "0"
[[4]] [1] "0" "0" "0" "1" "0" "0"
我想要得到这样的东西:
[[1]] [1] "010000"
[[2]] [1] "000001"
[[3]] [1] "010000"
[[4]] [1] "000100"
现在我正在使用:
apply(do.call(rbind,myFunctioninCPP(),1,paste0,collapse="")
得到我想要的东西。
我想知道是否有可能以这种方式获得更加“开箱即用”的 myFunctioninCPP() 结果。有什么建议吗?
最佳答案
采用以下代码,出于演示目的,该代码采用普通的 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();
}
现在,使用 sourceCpp
将函数加载到 R 中,并从 *apply
循环内部调用它。
## 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"
关于c++ - Rcpp 中的折叠 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35330439/