intmain(){ int i = 0; for (int z = 1; true; ++z) { for (int x = 1; x < z; ++x) { for (int y = x; y < z; ++y) { if (x * x + y * y == z * z) { printf("(%d,%d,%d)\n", x, y, z); if (++i == 10) goto done; } } } } done:; }
template<classF> voidgenerate_triples(Ff) { for (int z = 1; true; ++z) { for (int x = 1; x < z; ++x) { for (int y = x; y < z; ++y) { if (x*x + y * y == z * z) { bool stop = boolify(f)(std::make_tuple(x, y, z)); if (stop) return; } } } } }
template<classF> voidgenerate_triples(Ff) { for (int z = 1; true; ++z) { for (int x = 1; x < z; ++x) { for (int y = x; y < z; ++y) { if (x*x + y * y == z * z) { bool stop = boolify(f)(std::make_tuple(x, y, z)); if (stop) return; } } } } }
auto triples() -> generator<std::tuple<int, int, int>> { for (int z = 1; true; ++z) { for (int x = 1; x < z; ++x) { for (int y = x; y < z; ++y) { if (x*x + y * y == z * z) { co_yieldstd::make_tuple(x, y, z); } } } } }
intmain(){ auto g = triples(); for (int i = 0; i < 10; ++i) { g.move_next(); auto triple = g.current_value(); std::cout << '(' << std::get<0>(triple) << ',' << std::get<1>(triple) << ',' << std::get<2>(triple) << ')' << '\n'; } }
// A sample standard C++20 program that prints // the first N Pythagorean triples. #include<iostream> #include<optional> #include<range/v3/all.hpp> usingstd::get; usingstd::optional; usingstd::make_tuple; usingstd::cout; using ranges::view_interface; using ranges::iterator_t; namespace view = ranges::v3::view;
// maybe_view defines a view over zero or one // objects. template<classT> structmaybe_view : view_interface<maybe_view<T>> { maybe_view() = default; maybe_view(T t) : data_(std::move(t)) { } T const *begin()constnoexcept{ return data_ ? &*data_ : nullptr; } T const *end()constnoexcept{ return data_ ? &*data_ + 1 : nullptr; } private: optional<T> data_{}; }; // "for_each" creates a new view by applying a // transformation to each element in an input // range, and flattening the resulting range of // ranges. // (This uses one syntax for constrained lambdas // in C++20.) inlineconstexprauto for_each = [](auto&& r, auto fun) { returndecltype(r)(r) | view::transform(std::move(fun)) | view::join; }; // "yield_if" takes a bool and a value and // returns a view of zero or one elements. inlineconstexprauto yield_if = [](bool b, auto x) { return b ? maybe_view{std::move(x)} : maybe_view<decltype(x)>{}; }; intmain(){ // Define an infinite range of all the // Pythagorean triples: using view::iota; auto triples = for_each(iota(1), [](int z) { return for_each(iota(1, z+1), [=](int x) { return for_each(iota(x, z+1), [=](int y) { return yield_if(x*x + y*y == z*z, make_tuple(x, y, z)); }); }); }); // Display the first 10 triples for(auto triple : triples | view::take(10)) { cout << '(' << get<0>(triple) << ',' << get<1>(triple) << ',' << get<2>(triple) << ')' << '\n'; } }