Is there a C++ way of implementing/equivalent of the which() function in R?

Viewed 110

I'm re-writing an R program in c++. I'm wondering if there's a c++ equivalent or way of achieving the same result as the which() function in R. Here's what the which() function effectively accomplishes:

# A sequence 
x <- c(10, 20, 30, 40, 50)
# This should return a numerical index (1, 2) since only the first two elements are <= 20
which(x <= 20)

So which() essentially tests the expression and returns the TRUE indices of the logical object. I tried searching for an Rcpp sugar but can't seem to find one. There's which_max() and which_min(), which return the numerical indices for the max and min elements, respectively. I could always use the R function in Rcpp, but I'm interested in learning the c++ way if possible.

1 Answers

I don't have a C++20 compatible compiler at hand this moment so I didn't test this. But with C++20 and ranges you should be able to do something like this : Note this won't return the indices, but a view on the actual values.

#include <iostream>
#include <ranges>

// setup a predicate
auto which = [](const int& value ) { return value <= 20; };

int main()
{
    // or you can use std::vector
    std::array x{10,20,30,40,50};

    // create a filtered result
    auto result  = x | std::views::filter(which);

    return 0;
}
Related