我试图将字符向量(即字符串向量)从R传递到C/C++以进行排序和其他目的.使用Rcpp时,可以使用以下代码轻松完成:
#include <Rcpp.h>
#include <vector>
#include <string>
using namespace Rcpp;
// [[Rcpp::export]]
CharacterVector sort(CharacterVector x) {
std::sort(x.begin(), x.end());
return x;
}
Run Code Online (Sandbox Code Playgroud)
但是,由于这是我在这个软件包中唯一计划使用的C++,因此引入对Rcpp的依赖似乎不值得.没有它就做同样的事情并不容易.整数很容易:
#include <R.h>
#include <Rdefines.h>
#include <algorithm>
#include <string.h>
using namespace std;
SEXP sort(SEXP x) {
int* xx = INTEGER(x);
std::sort(xx, xx+LENGTH(x));
return(x);
}
Run Code Online (Sandbox Code Playgroud)
但没有std::vector<string>或char**相当于INTEGER().
如何在不向Rcpp引入依赖的情况下模拟相同的代码?
这里有一些问题讨论如何使用CHAR(STRING_ELT())转换单个字符串,但不清楚如何转换为字符串数组/向量.