C 通过随机选择其元素从两个元组制成元组

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

本文关键字:元组 两个 随机 选择 元素      更新时间:2023-10-16

我确切想要的是:我有一对具有未知类型和未知数参数的元组,但是这两个元组和可变计数的类型正是同样,例如:

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

让我们称这些元组为a和b

现在,我想通过以下方式从这两个具有完全相同类型和参数计数(std::tuple<Ts...>)的新元组中:

1。随机选择元素A或B作为元素(我想我可以通过调用STD :: vasteriment :: rand_int(0,1)或其他生成器来做到这一点。

2。将此元素放入新的元组中(我们称其为c)(也许std ::实验:: 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
            );
        };