25.5 Standard Template Library

STL provides powerful data structures and algorithms for C++.

Iterators

Iterators are used extensively in the STL to abstract away details of underlying data structures.

If you an iterator it, you can:

  • Get the value by ‘dereferencing’ with *it
  • Advance to the next value with ++it
  • Compare iterators (locations) with ==

Algorithms


#include <algorithm>
#include <Rcpp.h>

using namespace Rcpp;
 
 
// Explicit iterator version
 
// [[Rcpp::export]]
NumericVector square_C_it(NumericVector x){
  NumericVector out(x.size());
  // Each container has its own iterator type
  NumericVector::iterator in_it;
  NumericVector::iterator out_it;
  
  for(in_it = x.begin(), out_it = out.begin(); in_it != x.end();  ++in_it, ++out_it) {
    *out_it = pow(*in_it,2);
  }
  
  return out;
  
}
 
 
// Use algorithm 'transform'
  
// [[Rcpp::export]]
NumericVector square_C(NumericVector x) {
 
  NumericVector out(x.size());
 
 
  std::transform(x.begin(),x.end(), out.begin(),
            [](double v) -> double { return v*v; });
  return out;
}
square_C(c(1.0,2.0,3.0))
#> [1] 1 4 9
square_C_it(c(1.0,2.0,3.0))
#> [1] 1 4 9