[Rcpp-devel] What is the most efficient method to check if a Rcpp vector contains an element?
Hi Asis,
On 29 December 2013 at 12:50, Asis Hallab wrote:
| I am just wondering what would be the recommended and most efficient way to | check, if a Rcpp Vector contains a given element? | | If I am not mistaken the C++ standard approach for very large std::vectors | would be to first sort them and then perform a binary search: | | http://stackoverflow.com/questions/571394/how-to-find-an-item-in-a-stdvector | | What would be the Rcpp solution for the same task on a Rcpp vector?? Nothing wrong with what the accepted StackOverflow answer suggested: std::find(). | Should I convert my Rcpp Vector to a std::vector and do the above, as explained | on the stackoverflow blog? You don't need to convert. The STL types such as std::vector use iterators, and Rcpp was set up in such a way to make this possible. ## next line wrapped for mail, otherwise all on one line R> cppFunction('bool contains(NumericVector X, double z) { return std::find(X.begin(), X.end(), z)!=X.end(); }') R> contains(1:1e5,7777) [1] TRUE R> contains(1:1e5,-1) [1] FALSE R> One could of course expand on this by wrapping templates around it, but as a quick-and-dirty solution it is not too bad. Cheers, Dirk
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com