r-lib / cpp11

cpp11 helps you to interact with R objects using C++ code.
https://cpp11.r-lib.org/
Other
199 stars 46 forks source link

Random-access for `writable::r_vector::iterator` #222

Closed anthonynorth closed 3 years ago

anthonynorth commented 3 years ago

Would it be possible to implement random-access for writable::r_vector::iterator? This would (I think) allow the use of std::sort on writable r_vectors.

jimhester commented 3 years ago

Not easily, because the iterator uses a buffer internally to handle reading values from ALTREP vectors.

Maybe the best workaround would be falling back to using C pointers directly to do the sorting if you wanted. e.g.

cpp11::cpp_function(code = '
  cpp11::integers sort_int(cpp11::writable::integers x) {
    std::sort(INTEGER(x), INTEGER(x) + x.size());
    return x;
  }
  ')

sort_int(c(1L, 5L, 3L, 10L))
#> [1]  1  3  5 10

Created on 2021-08-16 by the reprex package (v2.0.0)

Note this will fully materialize any ALTREP vectors, but that can't really be helped if you are sorting the whole vector anyway.

anthonynorth commented 3 years ago

Thanks. I hadn't considered using the int pointer. My workaround was to construct a std vector, sort and return as_sexp. It turns out this is more efficient (for my use-case) anyway.