You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用views::zip转置向量的向量?编写等效Python zip的C++可变模板

实现等效于Python zip(*rng_of_rng)的C++可变模板转置函数

当编译期知晓外层容器的大小(即行数固定)时,我们可以用C++可变模板实现和Python transpose函数(基于zip(*rng_of_rng))等效的二维容器转置功能。

Python 原函数说明

Python 中的 transpose 函数通过 zip(*rng_of_rng) 实现:它接收一组可迭代对象,将每个可迭代对象的对应位置元素打包,返回由这些元素组成的新迭代器,本质是完成二维结构的转置。

C++ 可变模板实现

以下实现针对编译期大小固定的二维std::array(符合“编译期知晓外层大小”的要求):

#include <array>
#include <utility>

// 内部辅助实现:遍历所有列,提取每列元素组成转置后的行
template <typename T, size_t RowCount, size_t ColCount, size_t... ColIndices>
constexpr auto transpose_impl(const std::array<std::array<T, ColCount>, RowCount>& input, std::index_sequence<ColIndices...>) {
    // 提取指定列的所有行元素
    auto extract_column = [&input]<size_t Col>() {
        return []<size_t... RowIndices>(const auto& arr, std::index_sequence<RowIndices...>) {
            return std::array<T, RowCount>{arr[RowIndices][Col]...};
        }(input, std::make_index_sequence<RowCount>());
    };

    // 组合所有列的提取结果,生成转置后的二维数组
    return std::array<std::array<T, RowCount>, ColCount>{extract_column.template operator()<ColIndices>()...};
}

// 对外接口:自动推导编译期大小,触发转置逻辑
template <typename T, size_t RowCount, size_t ColCount>
constexpr auto transpose(const std::array<std::array<T, ColCount>, RowCount>& input) {
    return transpose_impl(input, std::make_index_sequence<ColCount>());
}

使用示例

#include <iostream>

int main() {
    // 定义2行3列的二维数组
    constexpr std::array<std::array<int, 3>, 2> original{{{1, 2, 3}, {4, 5, 6}}};
    // 编译期完成转置,得到3行2列的数组
    constexpr auto transposed = transpose(original);

    // 输出转置结果
    for (const auto& row : transposed) {
        for (int val : row) {
            std::cout << val << " ";
        }
        std::cout << "\n";
    }
    // 输出内容:
    // 1 4
    // 2 5
    // 3 6
    return 0;
}

实现说明

  • 利用C++20模板lambda简化列元素提取逻辑,通过std::index_sequence在编译期遍历行和列的索引,避免运行时循环开销。
  • 整个转置过程在编译期完成(使用constexpr),适合对性能要求较高且容器大小固定的场景。
  • 仅支持编译期大小固定的容器(如std::array),若需处理运行时动态大小的std::vector,则需改用运行时循环实现。

内容的提问来源于stack exchange,提问作者Tom Huntington

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:15:48