I have several vectors of either int
s or double
s:
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);
});
Is this possible? (I'm using C++14)
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.
(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 = ∅.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With