gpt4 book ai didi

c++ - 在 Rcpp 中使用 NumericVector 编写条件语句是否有更简单的方法?

转载 作者:行者123 更新时间:2023-11-28 01:25:41 26 4
gpt4 key购买 nike

我正在尝试使用 Rcpp 编写一些代码,并且我正在尝试了解条件语句如何在逻辑 vector 之间工作,因为它们是通过使用 NumericVector 和 C++ 的 native bool 类型进行比较而产生的。

我确定的方法如下(最小可重现示例,我的示例更复杂):

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]

NumericVector compare(NumericVector a, NumericVector b) {
if (is_true(all(b <= a))) {
return a;
}
return b;
}

然而,is_true 和 all 似乎都是多余的(例如,在我没有向您展示的更复杂的情况下),a 和 b 的长度保证为 1。

现在我只是找到了一个荒谬的复杂技术,还是这是一个不幸的案例“这是我们所拥有的最好的方法(尽管有这样的边缘情况,但这种方法的理由比反对的理由更好)” ?

最佳答案

不幸的是,is_true()is_false() 需要与 all() Rcpp 糖函数一起使用,因为:

The actual return type of all(X) is an instance of the SingleLogicalResult template class, but the functions is_true and is_false may be used to convert the return value to bool.

比较http://thecoatlessprofessor.com/programming/unofficial-rcpp-api-documentation/#all


解决这个问题的唯一方法是自己实现循环(@Aconcagua 暗示):

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector compare_loop(Rcpp::NumericVector a, Rcpp::NumericVector b) {

if(a.size() != b.size()) Rcpp::stop("Lengths of a and b must be the same.");

for (int i = 0; i < a.size(); ++i) {
// take opposite of comparison or switch it to b[i] > a[i]
if ( !(b[i] <= a[i]) ) {
return b;
}
}

return a;
}

测试:

a = c(-1, 2, 3, 5)
b = c(-3, -2, 4, 3)

all.equal(compare_loop(a,b), compare(a,b))
# [1] TRUE

关于c++ - 在 Rcpp 中使用 NumericVector 编写条件语句是否有更简单的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53983393/

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