Arlen
Arlen

Reputation: 6835

How do I create a 2D Array in D?

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 []
}

Upvotes: 2

Views: 498

Answers (1)

ccjuju
ccjuju

Reputation: 507

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?

Upvotes: 2

Related Questions