我不知道如何用 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>
中的原因是internal::string_proxy<>
类 provides operator+
带签名
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(), res.end(), rhs.begin(), 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, rhs, sep = "")
# [1] "ac" "bd"
paste3(lhs, rhs)
# [1] "ac" "bd"
*/
关于c++ - 将 StringVector 与 Rcpp 连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43182003/