这可能是一个愚蠢的问题,但我认为 CharacterVector
的每个单独元素将是 std::string
.但是,这不起作用:
std::string hello(CharacterVector vec) {
std::string result = vec[0];
return result;
}
错误:候选构造函数不可行:第一个参数没有从“Proxy”(又名“string_proxy<16>”)到“const_pointer”(又名“const char *”)的已知转换
如果是这样,我们应该强制转换为
std::string
在我们获得像 empty()
这样的 C++ 好东西之前, 等等?
最佳答案
有时你需要帮助编译器。
转换器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>
这一切都被记录在案,并且有大量的例子。很有可能找到更智能的模板编程来自动化这种转换,如果是这样,我们很乐意看到一个补丁。
对于您问题的第二部分:这些来自 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>
关于string - Rcpp CharacterVector:为什么单个元素不是 std::strings?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23282849/