forked from r-lib/cpp11
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsum_rcpp.cpp
More file actions
70 lines (58 loc) · 1.5 KB
/
sum_rcpp.cpp
File metadata and controls
70 lines (58 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <Rcpp.h>
// clang-format off
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wattributes"
#endif
#ifdef __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wattributes"
#endif
// clang-format on
[[cpp11::register]] SEXP rcpp_sum_dbl_for_(SEXP x_sxp) {
Rcpp::NumericVector x(x_sxp);
R_xlen_t n = x.size();
double sum = 0.;
for (R_xlen_t i = 0; i < n; ++i) {
sum += x[i];
}
return Rf_ScalarReal(sum);
}
[[cpp11::register]] SEXP rcpp_sum_int_for_(SEXP x_sxp) {
Rcpp::IntegerVector x(x_sxp);
R_xlen_t n = x.size();
double sum = 0.;
for (R_xlen_t i = 0; i < n; ++i) {
sum += x[i];
}
return Rf_ScalarReal(sum);
}
[[cpp11::register]] SEXP rcpp_sum_dbl_foreach_(SEXP x_sxp) {
Rcpp::NumericVector x(x_sxp);
double sum = 0.;
for (const auto& val : x) {
sum += val;
}
return Rf_ScalarReal(sum);
}
[[cpp11::register]] SEXP rcpp_sum_dbl_accumulate_(SEXP x_sxp) {
Rcpp::NumericVector x(x_sxp);
return Rf_ScalarReal(std::accumulate(x.cbegin(), x.cend(), 0.));
}
[[cpp11::register]] SEXP rcpp_grow_(SEXP n_sxp) {
R_xlen_t n = REAL(n_sxp)[0];
Rcpp::NumericVector x;
R_xlen_t i = 0;
while (i < n) {
x.push_back(i++);
}
return x;
}
[[cpp11::register]] SEXP rcpp_push_and_truncate_(SEXP size_sxp) {
R_xlen_t size = INTEGER(size_sxp)[0];
// Allocate `size` worth of doubles (filled with garbage data)
Rcpp::NumericVector out(size);
// Push 1 more past the existing capacity
out.push_back(0);
return out;
}