Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call lambda with the cartesian product of values in multiple input vectors

I have several vectors of either ints or doubles:

std::vector<int>    iv = { 1, 2, 3, 4 };
std::vector<double> jv = { .5, 1., 1.5, 2. };
std::vector<int>    kv = { 5, 4, 3, 2 };

I need to process the cartesian product of each vector:

for (int i : iv)
{
    for (double j : jv)
    {
        for (int k : kv)
        {
            process(i, j, k);
        }
    }
}

I would like to flatten this into a single call

product(iv, jv, kv, [=](int i, double j, int k)
    {
        process(i, j, k);
    });
  • The number of input vectors is variable
  • The types stored in the input vectors are variable

Is this possible? (I'm using C++14)

like image 945
Steve Lorimer Avatar asked Sep 07 '18 17:09

Steve Lorimer


People also ask

What is the use of Cartesian product in C++?

then one simple use of it will be to define the cartesian product of two lists (of possibly different type) as: where Tuple is a constructor, and xs is bound to the first of two lists. The returned value is a function which can be applied to a second list.

Is the Cartesian product of sets commutative?

(v) The Cartesian product of sets is not commutative, i.e. A × B ≠ B × A (vi) The Cartesian product of sets is not associative, i.e. A × (B × C) ≠ (A × B) × C (vii) If A is a set, then A × ∅ = ∅ and ∅ × A = ∅.

How many elements are in the Cartesian product of a and B?

A has 3 elements and B also has 3 elements. The Cartesian Product has 3 x 3 = 9 elements. In general, if there are m elements in set A and n elements in B, the number of elements in the Cartesian Product is m x n Given two finite non-empty sets, write a program to print Cartesian Product.

What is recursive Cartesian product?

Recursive implementation for computing the Cartesian product of lists. In the pursuit of making it as interactive as possible, the parsing function ended up taking the most space. The product set expression must be supplied enclosed by double quotes.


Video Answer


1 Answers

Here's a short recursive version that just works with any iterables. It takes everything by const& for simplicity:

template <typename F>
void product(F f) {
    f();
}

template <typename F, typename C1, typename... Cs> 
void product(F f, C1 const& c1, Cs const&... cs) {
    for (auto const& e1 : c1) {
        product([&](auto const&... es){
            f(e1, es...);
        }, cs...);
    }   
}

Which would be:

product(process, iv, jv, kv);
like image 157
Barry Avatar answered Oct 11 '22 21:10

Barry