如何在 D 中创建二维数组?
这应该很简单,但事实并非如此。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题给我提供了另一种方法来声明预先确定动态数组的大小如下:
尽管有多种不同的方法来执行此操作,具体取决于您想要添加元素的任意程度。您当然会想选择最适合您的程序的样式,但这里有一些可能性:
或
或
最后,如果您知道数组在编译时的大小并且它永远不会改变,您可以创建一个相反,静态数组:
这些都使用自然的内置数组机制。您需要使用 Array 容器类有什么具体原因吗?
Another method I was clued into by this question to declare the size of a dynamic array in advance is as follows:
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:
or
or
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:
These all use the natural builtin array mechanism though. Is there a specific reason you need to use the Array container class?