this might be a stupid question but i thought that each individual element of a CharacterVector
would be a std::string
. However, this doesnt work:
std::string hello(CharacterVector vec) {
std::string result = vec[0];
return result;
}
Error: candidate constructor not viable: no known conversion from 'Proxy' (aka 'string_proxy<16>') to 'const_pointer' (aka 'const char *') for 1st argument
If so should we force a conversion to std::string
before we get the C++ goodies like empty()
, etc?
Sometimes you need to help the compiler.
The converter Rcpp::as<T>()
converts from R, the converter Rcpp::wrap()
converts to R.
R> cppFunction('std::string hello(CharacterVector vec) {
return as<std::string>(vec[0]); }')
R> hello(c("The", "quick", "brown", "fox"))
[1] "The"
R>
This is all documented, and there are copious examples. It may well be possible to find smarter template programming to automate this conversion too, and if so we'd love to see a patch.
For the second part of your question: these come from R, and does not know or have std::string
. We have lightweight wrapper classes which generally avoid copying. Hence Rcpp::CharacterVector
-- which you can convert to std::vector<std::string>
.
Edit late 2016: Note that we can also do
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With