Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to use the Cartesian product of two ranges to generate all coordinates for an n * m grid in C++

1 Answer

0 votes
#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)

*/

 



answered Aug 4 by avibootz

Related questions

2 answers 317 views
2 answers 331 views
2 answers 250 views
1 answer 187 views
3 answers 189 views
2 answers 176 views
...