#include <iostream>
#include <ranges>
/*
This program demonstrates how to generate all coordinates of a 4×5 grid
using the Cartesian product of two ranges in idiomatic modern C++.
We use:
- std::views::iota to generate integer ranges
- A helper function cartesian_product(...) that returns a lazy view
- Structured bindings for clarity
- No manual indexing loops; everything is expressed through ranges
*/
// A reusable Cartesian-product view generator.
// It takes two ranges and produces a range of pairs (a, b).
template <std::ranges::input_range R1, std::ranges::input_range R2>
auto cartesian_product(const R1& r1, const R2& r2) {
// The returned view lazily iterates over all pairs (x, y)
return std::views::transform(r1, [&](auto x) {
return std::views::transform(r2, [&, x](auto y) {
return std::pair{x, y};
});
}) | std::views::join;
}
int main() {
// Define the grid dimensions
constexpr int rows = 4; // n
constexpr int cols = 5; // m
// Create ranges [0, rows) and [0, cols)
auto row_range = std::views::iota(0, rows);
auto col_range = std::views::iota(0, cols);
// Generate Cartesian product of row_range × col_range
auto grid = cartesian_product(row_range, col_range);
// Print all coordinates
std::cout << "Coordinates of a " << rows << "×" << cols << " grid:\n";
for (auto [r, c] : grid) {
std::cout << "(" << r << ", " << c << ")\n";
}
}
/*
run:
Coordinates of a 4×5 grid:
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 0)
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 0)
(3, 1)
(3, 2)
(3, 3)
(3, 4)
*/