gpt4 book ai didi

c++ - 将 StringVector 与 Rcpp 连接起来

转载 作者:太空狗 更新时间:2023-10-29 19:40:17 25 4
gpt4 key购买 nike

我不知道如何用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com