簡體   English   中英

在輸入向量的笛卡爾積中創建第 n 個元素的元組

[英]create tuple of nth element in the cartesian product of input vectors

我有一個 python 函數,它返回多個輸入數組的笛卡爾積中的第 n 個元素

def prod(n, arrs):
    out = []

    for i,arr in enumerate(arrs):
        denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
        idx = n // denom % len(arr)
        out.append( arr[idx] )

    return out

這很好用:

a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]

for n in range(20, 30):
    i = prod(n, [a, b, c])
    print(n, i)
 [1000, 3.0, -2] [1000, 3.0, -1] [1000, 3.0, 0] [1000, 3.0, 1] [1000, 3.0, 2] [1000, 3.5, -2] [1000, 3.5, -1] [1000, 3.5, 0] [1000, 3.5, 1] [1000, 3.5, 2]

現在我想把它翻譯成 C++(最大標准 C++-17)

template<typename... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs) 
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    // template magic here
}

有人可以幫助我使用上述公式構建元組所需的模板魔術嗎?

首先,為了簡單起見,讓我們自動推導出函數的返回類型。

接下來,索引序列是整潔的。 有了他們,就可以做到。

使用 C++20,我們可以從 lambda 中的序列中獲取索引。 在此之前,我們需要一個額外的功能。

最后,我們必須從最后開始創建索引,要么存儲索引,然后以相反的順序使用它們,要么反轉生成的元組。

template <class T, std::size_t... Ns>
static auto prod_impl(std::size_t n, T tuple, std::index_sequence<Ns...>) {
    auto f = [&](auto N){ auto r = n % N; n /= N; return r; };
    auto x = std::forward_as_tuple(std::get<(sizeof...(Ns)) - Ns - 1>(tuple)[f(std::get<(sizeof...(Ns)) - Ns - 1>(tuple).size())]...);
    return std::forward_as_tuple(std::get<(sizeof...(Ns)) - Ns - 1>(x)...);
}

template<class... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs) {
    return prod_impl(n, std::forward_as_tuple(vs...), std::make_index_sequence<sizeof...(vs)>());
}

使用索引數組的內部函數的更簡單替代方法:

template <class T, std::size_t... Ns>
static auto prod_impl(std::size_t n, T tuple, std::index_sequence<Ns...>) {
    auto f = [&](auto N){ auto r = n % N; n /= N; return r; };
    std::size_t Is[] = { f(std::get<sizeof...(Ns) - Ns - 1>(tuple).size())... , 0};
    return std::forward_as_tuple(std::get<Ns>(tuple)[sizeof...(Ns) - Ns - 1]...);
}

我們可以使用“索引技巧”來獲取與不同向量相關聯的索引。

這為我們提供了以下 C++14 解決方案:

#include <tuple>
#include <vector>
#include <cstdlib>

using std::array;
using std::size_t;

template <size_t NDim>
constexpr array<size_t, NDim> delinearize_coordinates(
    size_t n, array<size_t, NDim> dimensions) 
{
    // This might be optimizable into something nicer, maybe even a one-liner
    array<size_t, NDim> result{};
    for(size_t i = 0; i < NDim; i++) {
        result[NDim-1-i] = n % dimensions[NDim-1-i];
        n = n / dimensions[NDim-1-i];
    };
    return result;
}

template<size_t... Is, typename... Ts>
auto prod_inner(
    std::index_sequence<Is...>,
    size_t n, 
    const std::vector<Ts>&... vs) 
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    auto vs_as_tuple = std::make_tuple( vs ... );
    auto coordinates = delinearize_coordinates<sizeof...(Ts)>(n, { vs.size()... });
    return { std::get<Is>(vs_as_tuple)[coordinates[Is]] ... };
}

template<typename... Ts>
auto prod(size_t n, const std::vector<Ts>&... vs) 
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    return prod_inner(std::make_index_sequence<sizeof...(Ts)>{}, n,
        std::forward<const std::vector<Ts>&>(vs)...);
}

筆記:

  • 與您的代碼不同,我已經分解了將單個數字轉換為坐標序列的函數。
  • 如果您提供自己的make_index_sequence我認為您可以將其歸結為 C++11。

其他答案已經提到了索引技巧。 這是我的嘗試,盡可能直接從您的 python 代碼轉換:

template <typename T, std::size_t... I>
auto prod_impl(std::size_t n, T tuple, std::index_sequence<I...>) {
    std::array sizes{ std::size(std::get<I>(tuple))... };
    auto enumerator = [&sizes,n](std::size_t i, auto&& arr) -> decltype(auto) {
        auto denom = std::accumulate(std::begin(sizes) + i + 1, std::end(sizes), 1, std::multiplies<>{});
        auto idx = (n / denom) % std::size(arr);
        return arr[idx];
    };

    return std::forward_as_tuple(enumerator(I, std::get<I>(tuple))...);
}

template<typename... Ts, typename Is = std::index_sequence_for<Ts...>>
auto prod(std::size_t n, const std::vector<Ts>&... vs) {
    return prod_impl(n, std::forward_as_tuple(vs...), Is{});
}

(現場示例: http : //coliru.stacked-crooked.com/a/a8b975c29d429054

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM