c – 将StringVector与Rcpp连接
发布时间:2020-12-16 10:37:18 所属栏目:百科 来源:网络整理
导读:我无法弄清楚如何用Rcpp连接2个字符串;当我怀疑有一个明显的答案时,文档没有帮助我. http://gallery.rcpp.org/articles/working-with-Rcpp-StringVector/ http://gallery.rcpp.org/articles/strings_with_rcpp/ StringVector concatenate(StringVector a,Str
我无法弄清楚如何用Rcpp连接2个字符串;当我怀疑有一个明显的答案时,文档没有帮助我.
http://gallery.rcpp.org/articles/working-with-Rcpp-StringVector/ http://gallery.rcpp.org/articles/strings_with_rcpp/ StringVector concatenate(StringVector a,StringVector b) { StringVector c; c= ??; return c; } 我希望这个输出: a=c("a","b"); b=c("c","d"); concatenate(a,b) [1] "ac" "bd" 解决方法
可能有几种不同的方法可以解决这个问题,但这里有一个使用std :: transform的选项:
#include <Rcpp.h> using namespace Rcpp; struct Functor { std::string operator()(const std::string& lhs,const internal::string_proxy<STRSXP>& rhs) const { return lhs + rhs; } }; // [[Rcpp::export]] CharacterVector paste2(CharacterVector lhs,CharacterVector rhs) { std::vector<std::string> res(lhs.begin(),lhs.end()); std::transform( res.begin(),res.end(),rhs.begin(),res.begin(),Functor() ); return wrap(res); } /*** R lhs <- letters[1:2]; rhs <- letters[3:4] paste(lhs,rhs,sep = "") # [1] "ac" "bd" paste2(lhs,rhs) # [1] "ac" "bd" */ 首先将左手表达式复制到std :: vector< std :: string>的原因是内部:: string_proxy<>带有签名的provides std::string operator+(const std::string& x,const internal::string_proxy<STRSXP>& y) 而不是,例如, operator+(const internal::string_proxy<STRSXP>& x,const internal::string_proxy<STRSXP>& y) 如果您的编译器支持C 11,则可以稍微清理一下: // [[Rcpp::plugins(cpp11)]] #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] CharacterVector paste3(CharacterVector lhs,CharacterVector rhs) { using proxy_t = internal::string_proxy<STRSXP>; std::vector<std::string> res(lhs.begin(),lhs.end()); std::transform(res.begin(),[&](const std::string& x,const proxy_t& y) { return x + y; } ); return wrap(res); } /*** R lhs <- letters[1:2]; rhs <- letters[3:4] paste(lhs,sep = "") # [1] "ac" "bd" paste3(lhs,rhs) # [1] "ac" "bd" */ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |