2

This should be simple enough, but it's not.

import std.container, std.stdio;

void main(){

  alias Array!double _1D;
  alias Array!_1D _2D;

  _1D a = _1D();
  _2D b = _2D();
  a.insert(1.2);
  a.insert(2.2);
  a.insert(4.2);
  b.insert(a);
  writeln(b[0][]);  // prints [1.2, 2.2, 4.2], then throws exception

  _2D c = _2D();
  c.insert(_1D());
  c[0].insert(3.3);
  c[0].insert(2.2);
  c[0].insert(7.7);
  writeln(c[0][]);  // prints []
}
4

1 回答 1

2

这个问题提示我提前声明动态数组的大小的另一种方法如下:

auto matrix = new double[][](3, 2);  // elements can be appended/removed

尽管根据您想要添加元素的任意程度,有多种不同的方法可以做到这一点。您当然会想要选择最适合您的程序的风格,但这里有一些可能性:

double[][] matrix = [[1.1, 1.2], [2.3, 2.4], [3.5, 3.6]];

或者

double[][] matrix;
matrix ~= [1.1, 1.2];
matrix ~= [2.3, 2.4];
matrix ~= [3.5];
matrix[2] ~= 3.6;

或者

double[][] matrix = new double[][](1,0);
matrix[0].length = 2;
matrix[0][0] = 1.1;
matrix[0][1] = 1.2;

++matrix.length;
matrix[1] ~= 2.3;
matrix[1] ~= 2.4;

matrix ~= new double[](0);
matrix[$-1] ~= [3.5, 3.6];

最后,如果您在编译时知道数组的大小并且它永远不会改变,那么您可以创建一个静态数组:

double[2][3] staticMatrix;            // size cannot be changed

这些都使用了自然的内置数组机制。是否有特定原因需要使用 Array 容器类?

于 2012-01-06T11:08:45.203 回答