使用std :: unique_ptr的双(二维)数组 [英] Double (two-dimensional) array using std::unique_ptr

查看:123
本文介绍了使用std :: unique_ptr的双(二维)数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由指针分配的双精度数组。

I have a double array allocated by pointer to pointer.

  // pointer to pointer
  int **x = new int *[5];   // allocation
  for (i=0; i<5; i++){
      x[i] = new int[2];
  }

  for (i=0; i<5; i++){      // assignment
      for (j=0; j<2; j++){
          x[i][j] = i+j;
      }
  }

  for (i=0; i<5; i++)   // deallocation
      delete x[i];
  delete x;

我正在尝试使用 unique_ptr

std::unique_ptr<std::unique_ptr<int>[]> a(new std::unique_ptr<int>[5]);
  for (i=0; i<5; i++)
      a[i] = new int[2];

,但不断出现错误,指出没有运算符=匹配这些操作数。我在这里做错了什么?

but kept getting an error saying that no operator = matches these operands. What I am doing wrong here?

推荐答案

您无法分配 int * std :: unique_ptr< int []> ,这就是导致您出错的原因。正确的代码是

You cannot assign a int* to a std::unique_ptr<int[]>, that is the cause for your error. The correct code is

      a[i] = std::unique_ptr<int[]>(new int[2]);

但是,piokuc是正确的,使用 unique_ptr 用于数组,这就是 std :: vector std :: array 的目的,

However, piokuc is correct, that it is highly unusual to use unique_ptr for arrays, as that's what std::vector and std::array are for, depending on if the size is known ahead of time.

//make a 5x2 dynamic jagged array, 100% resizable any time
std::vector<std::vector<int>> container1(5, std::vector<int>(2)); 
//make a 5x2 dynamic rectangular array, can resize the 5 but not the 2
std::vector<std::array<int, 2>> container1(5); 
//make a 5x2 automatic array, can't resize the 2 or 5 but is _really fast_.
std::array<std::array<int, 2>, 5> container;

所有这些都可以初始化和使用,与您已有的代码相同,除了它们更容易构建,而且您不必销毁它们。

All of these can be initialized and used just the same as the code you already had, except they're easier to construct, and you don't have to destroy them.

这篇关于使用std :: unique_ptr的双(二维)数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆