如何在 D 中创建二维数组?

发布于 2024-12-25 03:18:44 字数 447 浏览 1 评论 0原文

这应该很简单,但事实并非如此。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

极致的悲 2025-01-01 03:18:44

这个问题给我提供了另一种方法来声明预先确定动态数组的大小如下:

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 容器类有什么具体原因吗?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文