Rcpp CharacterVector:为什么不是单个元素std :: strings?

dai*_*ish 6 string r rcpp

这可能是一个愚蠢的问题,但我认为a的每个元素CharacterVector都是一个std::string.但是,这不起作用:

std::string hello(CharacterVector vec) {
   std::string result = vec[0];
   return result;
}
Run Code Online (Sandbox Code Playgroud)

错误:候选构造函数不可行:第一个参数没有已知的从'Proxy'(又名'string_proxy <16>')到'const_pointer'(又名'const char*')的转换

如果是这样的话,我们应该std::string在获得C++好东西等之前强制进行转换empty()

Dir*_*tel 5

有时您需要帮助编译器.

该转换器Rcpp::as<T>()转换 R,所述转换器Rcpp::wrap()转换 R.

R> cppFunction('std::string hello(CharacterVector vec) { 
                                return as<std::string>(vec[0]); }')
R> hello(c("The", "quick", "brown", "fox"))
[1] "The"
R> 
Run Code Online (Sandbox Code Playgroud)

这些都记录在案,并有大量的例子.很可能找到更智能的模板编程来自动化这种转换,如果是这样,我们很乐意看到一个补丁.

对于你问题的第二部分:这些来自R,并且不知道或不具备std::string.我们有轻量级的包装类,通常避免复制.因此Rcpp::CharacterVector- 你可以转换为std::vector<std::string>.

编辑2016年末: 请注意,我们也可以这样做

R> cppFunction("std::string f(CharacterVector x,int i) {return std::string(x[i]);}")
R> foo(c("The", "quick", "brown", "fox"), 1)
[1] "quick"
R> 
Run Code Online (Sandbox Code Playgroud)