Skip to content

Instantly share code, notes, and snippets.

@tbfleming
Last active January 14, 2018 14:33
Show Gist options
  • Save tbfleming/756e6c6e0c4997176bd513cc2071271f to your computer and use it in GitHub Desktop.
Save tbfleming/756e6c6e0c4997176bd513cc2071271f to your computer and use it in GitHub Desktop.
cib demo: Range v3 comprehensions example
// Range v3 library
//
// Copyright Eric Niebler 2013-present
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
// cib:{"fetch":"https://cdn.rawgit.com/tbfleming/cib-zips/816dc978/range-v3-0.3.0.zip", "system_includes":["range-v3-0.3.0/include"], "unzip_compiler":true}
#include <iostream>
#include <range/v3/all.hpp>
using namespace ranges;
int main()
{
// Define an infinite range containing all the Pythagorean triples:
auto triples =
view::for_each(view::ints(1), [](int z)
{
return view::for_each(view::ints(1, z+1), [=](int x)
{
return view::for_each(view::ints(x, z+1), [=](int y)
{
return yield_if(x*x + y*y == z*z, std::make_tuple(x, y, z));
});
});
});
//// This alternate syntax also works:
//auto triples = view::ints(1) >>= [] (int z) { return
// view::ints(1, z+1) >>= [=](int x) { return
// view::ints(x, z+1) >>= [=](int y) { return
// yield_if(x*x + y*y == z*z,
// std::make_tuple(x, y, z)); };}; };
// Display the first 100 triples
RANGES_FOR(auto triple, triples | view::take(100))
{
std::cout << '('
<< std::get<0>(triple) << ','
<< std::get<1>(triple) << ','
<< std::get<2>(triple) << ')' << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment