diff --git a/CMakeLists.txt b/CMakeLists.txt index 82d9ae9..cef10de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -68,6 +68,7 @@ if(BUILD_TESTING AND ${KDALGORITHMS_BUILD_TEST}) src/kdalgorithms_bits/zip.h src/kdalgorithms_bits/tuple_utils.h src/kdalgorithms_bits/invoke.h + src/kdalgorithms_bits/cartesian_product.h tests/tst_kdalgorithms.cpp tests/tst_constraints.cpp diff --git a/Documentation/algorithms.md b/Documentation/algorithms.md index bc92ccb..dd7e0f8 100644 --- a/Documentation/algorithms.md +++ b/Documentation/algorithms.md @@ -41,6 +41,7 @@ Other - partitioned - multi_partitioned - zip +- product @@ -953,3 +954,34 @@ auto result = kdalgorithms::zip(v1, v2); ``` See [boost::compine](https://www.boost.org/doc/libs/1_81_0/libs/range/doc/html/range/reference/utilities/combine.html) for similar algorithm in boost, and [std::ranges::views::zip](https://en.cppreference.com/w/cpp/ranges/zip_view) for the C++23 version. + + +cartesian_product +----------------------------- +cartesian_product takes a number of containers and returns a cartesian product of the items. + +``` +const std::array x = {'A', 'B'}; +const std::vector y = {1, 2, 3}; +const std::list z = {"α", "β", "γ", "δ"}; + +auto result = kdalgorithms::product(x, y, z); +// result is: +// std::vector>{ +// {'A', 1, "α"}, {'A', 1, "β"}, {'A', 1, "γ"}, {'A', 1, "δ"}, +// {'A', 2, "α"}, {'A', 2, "β"}, {'A', 2, "γ"}, {'A', 2, "δ"}, +// {'A', 3, "α"}, {'A', 3, "β"}, {'A', 3, "γ"}, {'A', 3, "δ"}, +// {'B', 1, "α"}, {'B', 1, "β"}, {'B', 1, "γ"}, {'B', 1, "δ"}, +// {'B', 2, "α"}, {'B', 2, "β"}, {'B', 2, "γ"}, {'B', 2, "δ"}, +// {'B', 3, "α"}, {'B', 3, "β"}, {'B', 3, "γ"}, {'B', 3, "δ"}, +// }; +``` + +It is also possible to specify the return type: +``` +auto result = kdalgorithms::cartesian_product( x, y, z ); +// result is: +// std::deque>{ ... } +``` + +See [std::cartesian_product](https://en.cppreference.com/w/cpp/ranges/cartesian_product_view) diff --git a/src/kdalgorithms.h b/src/kdalgorithms.h index 697eb45..24ff7d3 100644 --- a/src/kdalgorithms.h +++ b/src/kdalgorithms.h @@ -10,6 +10,7 @@ #pragma once +#include "kdalgorithms_bits/cartesian_product.h" #include "kdalgorithms_bits/filter.h" #include "kdalgorithms_bits/find_if.h" #include "kdalgorithms_bits/generate.h" diff --git a/src/kdalgorithms_bits/cartesian_product.h b/src/kdalgorithms_bits/cartesian_product.h new file mode 100644 index 0000000..725730e --- /dev/null +++ b/src/kdalgorithms_bits/cartesian_product.h @@ -0,0 +1,51 @@ +/**************************************************************************** +** +** This file is part of KDAlgorithms +** +** SPDX-FileCopyrightText: 2024 Klarälvdalens Datakonsult AB, a KDAB Group company +** +** SPDX-License-Identifier: MIT +** +****************************************************************************/ + +#pragma once + +#include "transform.h" +#include "tuple_utils.h" +#include +#include + +namespace kdalgorithms { +namespace detail { + template