I like Eigen:
// [[Rcpp::depends(RcppEigen)]]
#include <RcppEigen.h>
using namespace Rcpp;
using Eigen::Map;
using Eigen::VectorXd;
typedef Map<VectorXd> MapVecd;
// [[Rcpp::export]]
NumericVector RcppEigenFun(NumericVector xx) {
const MapVecd x(as<MapVecd>(xx));
NumericVector LB(3);
LB[0] = x.minCoeff();
LB[1] = x.maxCoeff();
LB[2] = x.sum();
return LB;
}
Using it:
RcppEigenFun(3:7)
#[1] 3 7 25
Here is the corresponding function that uses sugar:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector RcppFun(NumericVector x) {
NumericVector LB(3);
LB[0] = min(x);
LB[1] = max(x);
LB[2] = sum(x);
return LB;
}
Benchmarks:
set.seed(42)
x <- rnorm(1e5)
library(microbenchmark)
microbenchmark(RcppEigenFun(x), RcppFun(x))
#Unit: microseconds
# expr min lq median uq max neval
# RcppEigenFun(x) 101.425 101.807 101.948 102.1785 123.095 100
# RcppFun(x) 1480.187 1480.552 1480.889 1489.0045 1550.173 100