Skip to content

Instantly share code, notes, and snippets.

@daniel-j-h
Created September 22, 2016 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniel-j-h/64289799c9f94a243173750800e53e38 to your computer and use it in GitHub Desktop.
Save daniel-j-h/64289799c9f94a243173750800e53e38 to your computer and use it in GitHub Desktop.
Transform Iterator Lazy View for @jakepruitt
#include <iostream>
#include <vector>
#include <utility>
#include <boost/iterator/transform_iterator.hpp>
// Takes arbitrary [first,last) iterator range, returns pair of [first,last)-transform iterators applying fn on the fly
template <typename Iter>
auto xform(Iter first, Iter last) {
// dummy function requiring values in the range to be convertible with to_string
auto fn = [](auto v){ return std::to_string(v); };
// lazy [first,last) transform iterator range, nothing is done so far
auto tfirst = boost::make_transform_iterator(first, fn);
auto tlast = boost::make_transform_iterator(last, fn);
return make_pair(tfirst, tlast);
}
int main() {
std::vector<int> v{10, 2, 30, 4};
auto range = xform(begin(v), end(v));
// only now the function is getting applied on the fly
for (auto it = range.first; it != range.second; ++it)
std::cout << it->size() << std::endl;
// note how we can do ->size() since it's a std::string now because we apply fn on the fly taking int and returning std::string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment