[Rcpp-devel] What is the most efficient method to check if a Rcpp vector contains an element?
Dirk Eddelbuettel
edd at debian.org
Sun Dec 29 16:39:33 CET 2013
Asis,
On 29 December 2013 at 09:26, Dirk Eddelbuettel wrote:
| On 29 December 2013 at 12:50, Asis Hallab wrote:
| | 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>
For completeness, a solution using any() which Romain had reminded us about.
This is possibly a little more idiomatic for Rcpp vectors, and shorter:
## next line wrapped for mail, otherwise all on one line
R> cppFunction('bool any(NumericVector X, double z) {
return any(X.begin(), X.end(), z); }')
R> any(1:1e5,7777)
[1] TRUE
R> any(1:1e5,-1)
[1] FALSE
R>
Dirk
--
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
More information about the Rcpp-devel
mailing list