[Rcpp-devel] fun(Times) with STL

Douglas Bates bates at stat.wisc.edu
Sat Jun 4 18:26:00 CEST 2011


On Sat, Jun 4, 2011 at 11:08 AM, Silkworth,David J.
<SILKWODJ at airproducts.com> wrote:
> I ran into this yesterday as I needed to get the position of the least time
> value in a small Que of times that I had extracted from a more complex
> structure.   I ended up with this problem during a separate work-around,
> which is a story I’d love to tell also.
>
> But, to the point.  I explored using STL in areas I had seen no examples
> previously.
>
> Nothing in the Rcpp sources suggested that min_element() or max_element()
> functions were supported, but I tried anyway.
>
> Only by taking note of the many compiler errors I generated was I able to
> come up with this stable line of code:
>
> double* myIterator = std::min_element (TimeQ.begin(), TimeQ.end());

The usual idiom is

double TQmin = *std::min_element(TimeQ.begin(), TimeQ.end());

> Now, in C++ training I flunked pointers and I skipped class for templates.
> But now I need to know what the heck is myIterator.
>
> So, I managed to put it into a single element NumericVector which I could
> return to R and examine.
>
> Okay, so this mysterious “iterator” thing is quite intuitively the expected
> result of a min_element function (with some pointer witchcraft included).
>
> To get the position of this item in the TimeQ I ended up building a small
> loop.
>
> for(int col=0; col<TimeQ.size(); col++)  {
>
> if(TimeQ[col] == *myIterator) {
>
> show_position[0]=col;
>
> break;  }   }
>
> My question is, “Is there a more elegant way to get the position value that
> I need”?    This code will be traversed 10’s of thousands of times in the
> function I am developing.
>
> Here is the full example as I have distilled it down:
>
> src <- '
>
> Rcpp::NumericVector TimeQ(arg1);
>
> Rcpp::NumericVector show_iterator(1);
>
> Rcpp::IntegerVector show_position(1);
>
>
>
> double* myIterator = std::min_element (TimeQ.begin(), TimeQ.end());
>
>
> show_iterator[0] = *myIterator;
>
>
>
> for(int col=0; col<TimeQ.size(); col++)  {
>
> if(TimeQ[col] == *myIterator) {
>
> show_position[0]=col;
>
> break;  }   }
>
>
>
> return show_position;   // alternatively: return show_iterator;
>
> '
>
>  fun <- cxxfunction(signature(arg1="numeric"),src,plugin="Rcpp")
>
>
>
>
>
>
> Times<-c(1944.285,2920.969,1720.230,1264.438,3607.507,1720.230,25176.020);
>
>
> fun_test<- fun(Times)
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
>


More information about the Rcpp-devel mailing list