std::ranges::cartesian_product — iterate over all combinations.
1#include <ranges>23std::vector<int> v1 = {1, 2};4std::vector<char> v2 = {'a', 'b', 'c'};56auto product = std::views::cartesian_product(v1, v2);78for (auto [x, y] : product) {9 std::cout << "(" << x << ", " << y << ") ";10}11// (1, a) (1, b) (1, c) (2, a) (2, b) (2, c)1213// Size is product of sizes14std::cout << product.size(); // 61516// Three ranges17std::vector<int> v3 = {10, 20};18auto prod3 = std::views::cartesian_product(v1, v2, v3);19for (auto [x, y, z] : prod3) {20 std::cout << "(" << x << "," << y << "," << z << ") ";21}22// (1,a,10) (1,a,20) (1,b,10) (1,b,20) (1,c,10) (1,c,20)23// (2,a,10) (2,a,20) (2,b,10) (2,b,20) (2,c,10) (2,c,20)2425// Lazy evaluation26auto first_few = product | std::views::take(3);27for (auto [x, y] : first_few) {28 std::cout << "(" << x << ", " << y << ") ";29}30// (1, a) (1, b) (1, c)3132// Nested for loop replacement33for (auto [i, j] : std::views::cartesian_product(34 std::views::iota(0, 3),35 std::views::iota(0, 3))) {36 std::cout << "(" << i << "," << j << ") ";37}
Benefits: