我正在尝试学习如何使用std.container中可用的各种容器结构,并且我无法理解如何执行以下操作:
1)如何创建空容器?例如,假设我有一个用户定义的类Foo
,并且想要创建一个应该包含Foo
对象的空DList .我应该使用什么语法?
2)假设a
并且b
都是DList!int
.我试着打电话a ~ b
,编译器告诉我,我不能.但是,我可以看到DList
那个运算符超载了.我错过了什么?
有三种方法可以创建新容器,
统一的方式,使用std.container.make
:
auto list1 = make!(DList!int)();
auto list2 = make!(DList!int)(1, 2);
Run Code Online (Sandbox Code Playgroud)使用struct initializer语法:
auto list1 = DList!int();
Run Code Online (Sandbox Code Playgroud)使用类的辅助函数:
auto tree1 = redBlackTree!int();
auto tree2 = redBlackTree!int(1, 2);
Run Code Online (Sandbox Code Playgroud)它们之间的区别在于一些数据结构是使用类实现的,一些是使用结构实现的.使用make
,你不需要知道,但第一种方式,因为没有有效的差异.
关于追加运算符,您需要追加范围DList!T
而不是DList!T
自身.例:
auto list1 = make!(DList!int)(1, 2);
auto list2 = make!(DList!int)(3, 4);
list1 ~= list2[]; //notice the square brackets, which represent obtaining a slice (InputRange) from the `DList`, or more specifically calling `opSlice`.
Run Code Online (Sandbox Code Playgroud)
作为更完整的使用示例,请检查以下内容:
import std.container;
import std.stdio;
class Foo {
int i;
this(int i) {
this.i = i;
}
void toString(scope void delegate(const(char)[]) sink) const {
// this is a non allocating version of toString
// you can use a normal `string toString()` function too
import std.string : format;
sink("Foo: %s".format(i));
}
}
void main() {
auto odds = make!(DList!Foo)();
odds.insert(new Foo(3));
odds.insert(new Foo(5));
writeln("Odds: ", odds[]);
odds.insertFront(new Foo(1));
writeln("Odds: ", odds[]);
auto evens = make!(DList!Foo)();
evens.insert(new Foo(2));
evens.insert(new Foo(4));
writeln("Evens: ", evens[]);
odds.insert(evens[]);
writeln("Odds then evens: ", odds[]);
odds ~= evens[];
writeln("Odds then evens x 2: ", odds[]);
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里在线运行:http://dpaste.dzfl.pl/f34b2ec8a445