Skip to content

Instantly share code, notes, and snippets.

@nthery
Last active June 17, 2022 07:23
Show Gist options
  • Save nthery/780b71d309fe7f1341e392603ce041a5 to your computer and use it in GitHub Desktop.
Save nthery/780b71d309fe7f1341e392603ce041a5 to your computer and use it in GitHub Desktop.
// Range demo
#include <iostream>
#include <algorithm>
#include <iterator>
#include <range/v3/all.hpp>
void first_class_range() {
// Classic STL: A range is just a pair of iterators
std::vector v1{42, 666, 1, 314 };
std::sort(v1.begin(), v1.end());
std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
// Range STL: A range is a first class entity
std::vector v2{42, 666, 1, 314 };
ranges::sort(v2);
ranges::copy(v2, ranges::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
void composition() {
std::vector v{1, 2, 3, 4, 5, 6, 7, 8, 9};
// Lazy function composition: no processing yet
auto first_5_odd_numbers_squared =
ranges::view::filter([](int n) { return (n & 1) != 0; }) |
ranges::view::take(5) |
ranges::view::transform([](int n) { return n * n; });
// copy() will pull data out of the pipeline
ranges::copy(v | first_5_odd_numbers_squared, ranges::ostream_iterator<int>(std::cout, " "));
}
int main() {
first_class_range();
composition();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment