比较Rcpp中的两个值而不转换为特定类型

Ste*_*reo 0 c++ r rcpp

我试图使用Rcpp比较C++中的两个通用R值.如何在不将它们转换为C++中的特定类型的情况下比较两个值?

解释我的问题的代码如下,

require("Rcpp")
require("inline")
src <- "return wrap(x1 == x2);"

fun <- cxxfunction(signature(x1 = "SEXP", x2 = "SEXP"), src, plugin = "Rcpp")

fun("a", "a")

to_cmp <- "a"

fun(to_cmp, to_cmp)
Run Code Online (Sandbox Code Playgroud)

它现在给我FALSETRUE它想要它屈服TRUETRUE.

由于我的目标是在C++中实现数据结构,我更倾向于使用潜在的用户定义==方法.

可能的方法

我试过的一种方法是,

要求( "RCPP")

src <- '
Language call("\`==\`", x1, x2);

return call.eval();
'

fun <- cxxfunction(signature(x1 = "SEXP", x2 = "SEXP"), src, plugin = "Rcpp")

fun("a", "a")

to_cmp <- "a"

fun(to_cmp, to_cmp)
Run Code Online (Sandbox Code Playgroud)

但是,当我运行这个时,我得到了 Error: could not find function "`==`"

coa*_*ess 5

使用通用SEXP输入对象标签,您处于正确的轨道上.为了实现这一点,除此之外还需要使用C++模板TYPEOF().先验使得比较函数中的正确向量创建能够与Rcpp糖连接,而后者使得能够进行正确的检查和分派.

#include <Rcpp.h>
using namespace Rcpp;

template <int RTYPE>
Rcpp::LogicalVector compare_me(Rcpp::Vector<RTYPE> x, Rcpp::Vector<RTYPE> y) {
    return x == y;
}

// [[Rcpp::export]]
Rcpp::LogicalVector compare_objects(SEXP x, SEXP y) {

    if (TYPEOF(x) == TYPEOF(y)) {
        switch (TYPEOF(x)) {
            case INTSXP:
                return compare_me<INTSXP>(x, y);
            case REALSXP:
                return compare_me<REALSXP>(x, y);
            case STRSXP:
                return compare_me<STRSXP>(x, y);
            default:
                Rcpp::stop("Type not supported");
        }
    } else {
        Rcpp::stop("Objects are of different type");
    }

    // Never used, but necessary to avoid the compiler complaining
    // about a missing return statement
    return Rcpp::LogicalVector(); 
}
Run Code Online (Sandbox Code Playgroud)

例:

to_cmp <- "a"
compare_objects(to_cmp, to_cmp)
Run Code Online (Sandbox Code Playgroud)

输出:

[1] TRUE
Run Code Online (Sandbox Code Playgroud)

另外,以上是用于Rcpp::sourceCpp().我鼓励您从使用切换inline到使用Rcpp::cppFunction()函数定义,因为它允许您专注于计算而不是设置.