簡體   English   中英

C ++通過隨機選擇元素從兩個元組中創建元組

[英]C++ Making tuple from two tuples by randomly choosing their elements

我想要什么:我有一對具有未知類型和未知數量的參數的元組,但這兩個元組和變量計數的類型完全相同,例如:

std::pair<std::tuple<Ts...>, std::tuple<Ts...>>

我們稱這些元組為A和B.

現在我想通過以下方式從這兩個具有完全相同類型和參數計數( std::tuple<Ts...> )的std::tuple<Ts...>創建一個新元組:

1.隨機選擇一個元素的元組A或B (我想我可以通過調用std :: experimental :: rand_int(0,1)或另一個生成器來實現)。

2.將此元素放在新元組中(讓我們稱之為C) (也許std :: experimental :: apply可能對第2點和第3點有任何幫助。)

3.重復步驟1-2,直到元組A和B結束

例:

A = std::tuple<double, int, long, int> {2.7, 1, 22, 4};
B = std::tuple<double, int, long, int> {12.4, 7, -19, 18};

在我想要接收的算法之后,例如:

C = std::tuple<double, int, long, int> {12.4, 1, 22, 18}; 

(或遵循此計划的A和B的任何其他組合)

不應該太難:

template <typename Tuple, std::size_t ...I>
Tuple rand_tuple_aux(const Tuple & a, const Tuple & b, std::index_sequence<I...>)
{
    return Tuple(std::get<I>(flip_coin() ? a : b)...);
}

template <typename ...Args>
std::tuple<Args...> rand_tuple(const std::tuple<Args...> & a,
                               const std::tuple<Args...> & b)
{
    return rand_tuple_aux(a, b, std::index_sequence_for<Args...>());
}

我知道有一個明顯的答案,所以我不會改變它,但我想添加我的解決方案(這是非常hackish所以不是真的建議,但我想讓這個功能成為一個lambda)。 父母類型:

std::pair<std::pair<std::tuple<Ts...>>, std::pair<std::tuple<Ts...>>>

(這就是為什么我用過汽車...)

這是代碼:

auto generate_child=[&](const auto& parents){
            auto genotype=std::experimental::apply(
                    [&](const auto&... mother){
                        return std::experimental::apply(
                                [&](const auto&... father){
                                    return std::make_tuple(
                                            (std::experimental::randint(0,1)?mother:father)...
                                    );
                                },
                                parents.second.second
                        );
                    },
                    parents.first.second
            );
            return std::make_pair(
                    std::experimental::apply(function,genotype),
                    genotype
            );
        };

暫無
暫無

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

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