如何测试 Rcpp::CharacterVector 元素是否相等? [英] How to test Rcpp::CharacterVector elements for equality?

查看:32
本文介绍了如何测试 Rcpp::CharacterVector 元素是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些简单的 Rcpp 代码示例.使用 Rcppinline 包,这非常容易.

I am trying to write some simple Rcpp code examples. This is remarkably easy with the Rcpp and inline packages.

但是我对如何测试两个字符元素是否相等感到困惑.以下示例比较两个字符向量的第一个元素.但我无法编译.

But I am stumped on how to test whether two character elements for equality. The following example compares the first elements of two character vectors. But I can't get it to compile.

有什么诀窍?

library(Rcpp)
library(inline)

cCode <- '
    Rcpp::CharacterVector cx(x);
    Rcpp::CharacterVector cy(y);
    Rcpp::LogicalVector r(1);
    r[0] = (cx[0] == cy[0]);
    return(r);
    '

cCharCompare <- cxxfunction(signature(x="character", y="character"), 
                            plugin="Rcpp", body=cCode)
cCharCompare("a", "b")

--

如果两个元素之一是常量,则使用 == 的比较非常有效.以下代码编译并给出预期结果:

The comparison using == works perfectly fine if one of the two elements is a constant. The following code compiles and gives expected results:

cCode <- '
    Rcpp::CharacterVector cx(x);
    Rcpp::LogicalVector r(1);
    r[0] = (cx[0] == "a");
    return(r);
    '

cCharCompareA <- cxxfunction(signature(x="character"), plugin="Rcpp", body=cCode)

cCharCompareA("a")
[1] TRUE

cCharCompareA("b")
[1] FALSE

推荐答案

@kohske 提供的非常好的(技术性)答案,但这里有更多 C++ 风格的内容:只需比较字符串!

Very nice (technical) answer by @kohske, but here is something more C++-ish: just compare strings!

library(inline)      ## implies library(Rcpp) when we use the plugin

cCode <- '
    std::string cx = Rcpp::as<std::string>(x);
    std::string cy = Rcpp::as<std::string>(y);
    bool res = (cx == cy);
    return(Rcpp::wrap(res));
    '

cCharCompare <- cxxfunction(signature(x="character", y="character"),
                            plugin="Rcpp", body=cCode)
cCharCompare("a", "b")

如果你真的只想比较字符串的第一个字符,那么你可以从 xx.c_str() 并索引它的初始元素,或者只是取消引用指向第一个字符的指针.

If you really want to compare just the first character of the strings, then you can go from x to x.c_str() and either index its initial element, or just dereference the pointer to the first char.

一个更 R-ish 的答案可能会扫过实际的字符串向量......

A more R-ish answer could maybe sweep over actual vectors of strings...

这篇关于如何测试 Rcpp::CharacterVector 元素是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆