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

↘锁芯ラ 提交于 2019-12-08 01:57:07

问题


I am wondering if there is a Rcpp way to convert an element or iterator of const CharacterVector& to std::string. If I try the following code

void as(const CharacterVector& src) {
    std::string glue;
for(int i = 0;i < src.size();i++) {
        glue.assign(src[i]);
}
}

a compiler-time error will occurred:

no known conversion for argument 1 from ‘const type {aka SEXPREC* const}’ to ‘const char*’

So far, I use C API to do the conversion:

glue.assign(CHAR(STRING_ELT(src.asSexp(), i)));

My Rcpp version is 0.10.2.

By the way, I do know there is a Rcpp::as.

glue.assign(Rcpp::as<std::string>(src[i]));

the above code will produce a runtime-error:

Error: expecting a string

On the otherhand, the following code run correctly:

typedef std::vector< std::string > StrVec;
StrVec glue( Rcpp::as<StrVec>(src) );

However, I do not want to create a temporal long vector of string in my case.

Thanks for answering.


回答1:


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>



回答2:


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];
}


来源:https://stackoverflow.com/questions/15380785/converting-element-of-const-rcppcharactervector-to-stdstring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!