Created
September 22, 2016 15:57
-
-
Save daniel-j-h/64289799c9f94a243173750800e53e38 to your computer and use it in GitHub Desktop.
Transform Iterator Lazy View for @jakepruitt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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
http://www.boost.org/doc/libs/1_61_0/libs/iterator/doc/transform_iterator.html