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 []
}
Arlen
  • 6,641
  • 4
  • 29
  • 61

1 Answers1

2

Another method I was clued into by this question to declare the size of a dynamic array in advance is as follows:

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

Though there are a variety of different ways to do it depending on how arbitrarily you want to add elements. You'll of course want to pick whichever style works best for your program, but here are some possibilities:

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

or

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

or

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];

and finally, if you know that the size of your array at compile time and it will not ever change, you can create a static array instead:

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

These all use the natural builtin array mechanism though. Is there a specific reason you need to use the Array container class?

Community
  • 1
  • 1
ccjuju
  • 507
  • 4
  • 15
  • It does not seem to me like he is questioning anything at all. He simply asked you if you have a specific reason for using the Array... Down-voting is too harsh IMHO. – DejanLekic Jan 07 '12 at 11:40
  • @DejanLekic The down-vote was for him not answering the question. There is a big difference between built-in arrays and Array. – Arlen Jan 07 '12 at 23:18
  • Sure there is a difference... It is your right to downvote yes, but I believe not voting up is punishment enough. :) – DejanLekic Jan 08 '12 at 11:03