gpt4 book ai didi

c++ - 将 std::array 拆分为较小尺寸的 std::array 的元组

转载 作者:行者123 更新时间:2023-11-30 03:55:49 25 4
gpt4 key购买 nike

我正在尝试拆分 std::array<T, N>成一个较小数组的元组,比如 std::tuple<std::array<T, N1>, std::array<T, N2>, ...>其中 N1 + N2 + ... = N.

namespace detail {
// Summation of the given values
template <class T>
constexpr T sum(const T& x) { return x; }

template <class T, class ...Args>
constexpr auto sum(const T& x, Args&&... args)
{ return x + sum(std::forward<Args>(args)...); }
}

template <class T, std::size_t... Ns>
constexpr
std::tuple<std::array<T, Ns>...>
f(const std::array<T, detail::sum(Ns...)>& x)
{
// How do I implement this function?
}

int main()
{
constexpr std::array<Foo, 5> arr = { ... };
constexpr auto t = f<Foo, 2,3>(arr);
}

其实我已经实现了f但它基于一个循环,该循环简单地创建一个空数组并复制给定数组的元素,但如果 T 不是 default_constructible 则它不起作用.

我尝试使用 std::integer_sequencestd::make_index_sequence ,但我想我完全迷失了方向。

谁能帮我实现这个功能?

最佳答案

template<class T,size_t...Is,size_t N>
std::array<T,sizeof...(Is)>
extract(std::array<T,N>const&,std::index_sequence<Is...>){
return {{arr[Is]...}};
}

现在我们只需要把 {1,2,3} 变成 {{0},{1,2},{3,4,5}}粗略地说,一切都是 C++ 索引序列(语法)。

{3,4,0} 映射到 {0,1,2} -- 子数组的索引计数。然后将 {3,4,0} x 1 映射到 {3,4,5,6} 并且其他类似。这为我们提供了子数组中的索引,我们将其提供给extract,而 bob 是你的叔叔。

template<size_t n, size_t...counts>
constexpr auto
foo( std::index_sequence<counts...> )
-> offset_seq<
sum_n<n>(counts...),
std::make_index_sequence<get_n<n,counts...> >
>{ return {}; }

要编写的各种助手是 {3,4,0} x 1{3,4,5,6} 部分,例如。

关于c++ - 将 std::array 拆分为较小尺寸的 std::array 的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28876299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com