Converting element of 'const Rcpp::CharacterVector&' to 'std::string'

主宰稳场 提交于 2019-12-06 12:42:23

I am confused as that what you want -- a CharacterVector is a vector of character strings (as in R) so you can only map it to std::vector<std::string> >. Here is a very simple, very manual example (and I thought we had auto-converters for this, but maybe not. Or no more.

#include <Rcpp.h>  

// [[Rcpp::export]] 
std::vector<std::string> ex(Rcpp::CharacterVector f) {  
  std::vector<std::string> s(f.size());   
  for (int i=0; i<f.size(); i++) {  
    s[i] = std::string(f[i]);  
  }  
  return(s);     
}

And here it is at work:

R> sourceCpp("/tmp/strings.cpp")
R> ex(c("The","brown","fox"))  
[1] "The"   "brown" "fox" 
R>

In Rcpp 0.12.7, I can use Rcpp::as<std::vector<std::string> >. The following function returns the second element of the test array:

std::string test() {
  Rcpp::CharacterVector test = Rcpp::CharacterVector::create("a", "z");
  std::vector<std::string> test_string = Rcpp::as<std::vector<std::string> >(test);
  return test_string[1];
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!