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
The real power of iterators comes from using them with STL algorithms.
A good reference is [https://en.cppreference.com/w/cpp/algorithm]
Book provides examples using
accumulate
andupper_buond
Another Example:
#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;
}