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

如何删除boost::multi_array中的首行或首列?

如何删除boost::multi_array中的首行或首列?

嘿,我来给你捋捋怎么在boost::multi_array里删掉首行或者首列~其实删掉最后一行/列本来就挺简单的,而要处理首行首列的话,咱们可以用库自带的索引生成器(index_gen)来创建原数组的视图,不需要复制数据,效率很高。给你看个完整的示例代码,把几种情况都包含进去了:

#include "boost/multi_array.hpp"
#include <iostream>

typedef boost::multi_array<double, 2> array_type;

// 辅助函数:打印数组
void print_array(const array_type& A){
  for ( size_t i=0; i < A.shape()[0]; i++ ) {
    for ( size_t j=0; j < A.shape()[1]; j++ )
      std::cout << A[i][j] << " ";
    std::cout << std::endl;
  }
}

int main () {
  
  // 创建一个5行3列的二维数组
  array_type A(boost::extents[5][3]);

  // 给数组元素赋值
  int values = 0;
  for(size_t i = 0; i < A.shape()[0]; ++i) {
    for(size_t j = 0; j < A.shape()[1]; ++j) {
        A[i][j] = values;
    }
    values++;
  }

  // 打印原数组
  std::cout << "原数组A:" << std::endl;
  print_array(A);

  // ------------ 各种删除操作示例 ------------
  array_type::index_gen indices;

  // 删除最后一行
  auto A_without_last_row = A[indices[0][A.shape()[0]-2]][indices[0][A.shape()[1]-1]];
  std::cout << "\n删除最后一行后的数组:" << std::endl;
  print_array(A_without_last_row);

  // 删除首行
  auto A_without_first_row = A[indices[1][A.shape()[0]-1]][indices[0][A.shape()[1]-1]];
  std::cout << "\n删除首行后的数组:" << std::endl;
  print_array(A_without_first_row);

  // 删除最后一列
  auto A_without_last_col = A[indices[0][A.shape()[0]-1]][indices[0][A.shape()[1]-2]];
  std::cout << "\n删除最后一列后的数组:" << std::endl;
  print_array(A_without_last_col);

  // 删除首列
  auto A_without_first_col = A[indices[0][A.shape()[0]-1]][indices[1][A.shape()[1]-1]];
  std::cout << "\n删除首列后的数组:" << std::endl;
  print_array(A_without_first_col);

  return 0;
}

简单解释下核心逻辑:

  • boost::multi_array的索引生成器index_gen可以帮我们快速指定要保留的数组范围,生成的是原数组的视图,不会额外占用内存
  • 删除首行:就是从索引1(第二行)开始,取到最后一行的范围
  • 删除首列:同理,从索引1(第二列)开始取到最后一列
  • 删除最后一行/列:则是取到倒数第二个索引为止,比如原数组有5行,就取0到3(共4行)

这样操作下来,就能轻松得到去掉首行/首列或者末行/末列的数组视图啦~

备注:内容来源于stack exchange,提问作者TMueller83

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 06:59:29