[Rcpp-devel] Dispatching based on SEXPTYPE

Hadley Wickham h.wickham at gmail.com
Wed Nov 21 22:35:29 CET 2012

>> I would perhaps advise you to have the unique1 overloads not to return the
>> stl object, as you are generating copies (although some may argue about
>> compiler optimizations).
> Ah, ok.  I don't have much intuition for when copies occur in C++.
>> I would advise to return include the call to wrap in your unique1.
> You mean just inline them in unique1, and not have the individual
> unique2 functions?

Like this?

// [[Rcpp::export]]
RObject unique3(RObject x) {
  NumericVector y1;
  IntegerVector y2;
  LogicalVector y3;

  std::tr1::unordered_set<double> set1;
  std::tr1::unordered_set<int> set2;
  std::tr1::unordered_set<bool> set3;

  switch(x.sexp_type()) {
    case REALSXP:
      y1 = as<NumericVector>(x);
      set1.insert(y1.begin(), y1.end());
      return wrap(set1);
    case INTSXP:
      y2 = as<IntegerVector>(x);
      set2.insert(y2.begin(), y2.end());
      return wrap(set2);
    case LGLSXP:
      y3 = as<LogicalVector>(x);
      set3.insert(y3.begin(), y3.end());
      return wrap(set3);
      Rf_error("Unsupported type");

It doesn't make any difference to the speed, apart from the logical
case, which I find surprising given that it should have the least
copying to do.


RStudio / Rice University

More information about the Rcpp-devel mailing list