[Rcpp-devel] fun(Times) with STL

Silkworth,David J. SILKWODJ at airproducts.com
Sat Jun 4 18:08:48 CEST 2011

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

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());

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

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) {			
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) {			
break;  }   }			
return show_position;	// alternatively: return show_iterator;	
 fun <- cxxfunction(signature(arg1="numeric"),src,plugin="Rcpp")

fun_test<- fun(Times)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20110604/15f84012/attachment-0001.htm>

More information about the Rcpp-devel mailing list