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

标签 c++ r concatenation rcpp

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

相关文章:

c++ - LLVM 预处理器显然不支持 ## 运算符?

rbind 列表并恢复名称

r - 如何按类别在 data.table 列中查找(而不是替换)前导 NA、间隙和最终 NA

r - model.frame.default : variable lengths differ 中的错误

python - 在 pandas 中连接 2 列 - AttributeError : 'DataFrame' object has no attribute 'concat'

windows - ffmpeg - 2 个文件 - 转换 -> 连接 -> 水印不起作用

c++ - 堆损坏在 C++ 中检测到错误

c++ - 翻译在 Qt 中不起作用

c++ - 静态局部变量什么时候出现?

c++ - .cpp 文件不会链接到 .h 文件