Rcpp调用的c++计数算法模板

c++ count algorithm template called by Rcpp

本文关键字:算法 调用 c++ Rcpp      更新时间:2023-10-16
Rcpp调用的C++计数算法,可以计算向量中特定元素的出现次数。应该使用模板。我的尝试:
countRcpp <-'
#include<iostream>
#include<vector>
using namespace std;
int val = as<int>(y);
NumericVector xx(x);
NumericVector::iterator iter;
int m = 0;
for(iter = xx.begin(); iter < xx.end(); iter++){
if(*iter == val) ++m;}
return(wrap(m));
'
countf <- cxxfunction(signature(x = "numeric", y = "numeric"),
body = countRcpp,
plugin = "Rcpp")
set.seed (1005) # set seed for sampling
x <- sample(1:5L, size = 10, replace = T) #L is Long integer. Keep the nunmber as integer. 
x # [1] 1 3 1 3 3 4 1 3 1 2
y <- 3L
y
countf(x,y) 

incl <- '
#include<iostream>
#include <algorithm>  
#include <vector> 
using namespace std;
template <typename S_Type, typename T>
typename iterator_traits<S_Type>::difference_type 
S_Type countR(S_Type first, S_Type last, const T & val){
typename iterator_traits<S_Type>::difference_type ret=0;
while (first !=last){
if(*first == val) ++ret;
++first;
}
return ret;
}
'
body_count <- '
#include<iostream>
#include<vector>
#include <algorithm>    
using namespace std;
NumericVector xx(x);
int n = xx.size();
NumericVector yy = xx + n;
int val = as<int>(y);
int pos = countR(xx, yy, val);
return wrap(pos);
'
countRcpp3 <- cxxfunction(signature(x = "numeric", y = "numeric"),
body = body_count,
includes = incl,
plugin = "Rcpp")

你能给我一些建议吗?或者你会推荐其他符合逻辑的任务吗?提前谢谢。

作为第一步,您可以提取具有签名的函数

int foo(Rcpp::IntegerVector x, int val)

从您的工作代码。然后,您可以将其泛化为对任何可迭代类型执行操作。签名:

template <typename T>
int foo(T x, typename std::iterator_traits<typename T::iterator>::value_type val) 

然而,我们不能用R来称呼它。如果R中的函数应该作用于不同的类型,那么它必须将SEXP作为参数。CCD_ 2然后可以用于确定R数据类型。将这些放在一起用于整数向量:

#include <Rcpp.h>
template <typename T>
int iter_count(T x, typename std::iterator_traits<typename T::iterator>::value_type val) { 
int m = 0;
for(typename T::iterator iter = x.begin(); iter < x.end(); ++iter) {
if(*iter == val) ++m;
}
return m;
}

// [[Rcpp::export]]
int count(SEXP x, SEXP val) {
switch( TYPEOF(x) ) {
case INTSXP: {
return iter_count(Rcpp::as<Rcpp::IntegerVector>(x),
Rcpp::as<Rcpp::IntegerVector>(val)(0));
}
default: {
Rcpp::stop("incompatible SEXP encountered");
}
}  
}

/*** R
set.seed (1005)
x <- sample(1:5L, size = 10, replace = T)
y <- 3L
count(x,y) 
*/

我在这里使用Rcpp属性:将其保存为.cpp文件并在其上使用Rcpp::sourceCpp("...")

顺便说一句,在你的代码中,这看起来很可疑:

NumericVector xx(x);
int n = xx.size();
NumericVector yy = xx + n;

你想要xx的终点吗?然后使用不是NumericVectorxx.end()end(xx)。您的代码创建了一个新的NumericVector,其中xx的内容已按xx的大小递增。这里使用Rcpp属性的等效代码:

Rcpp::cppFunction('NumericVector foo(NumericVector xx) {
int n = xx.size();
NumericVector yy = xx + n;
return yy;
}
')
set.seed(42)
foo(runif(3))
# [1] 3.914806 3.937075 3.286140