gpt4 book ai didi

containers - D: 不清楚如何使用 std.container 结构

转载 作者:行者123 更新时间:2023-12-01 09:57:56 27 4
gpt4 key购买 nike

我正在尝试学习如何使用 std.container 中可用的各种容器结构,但我无法理解如何执行以下操作:

1) 如何创建一个空容器?例如,假设我有一个用户定义的类 Foo,并且想要创建一个应该包含 Foo 对象的空 DList。我应该使用什么语法?

2) 假设ab 都是DList!int。我尝试调用 a ~ b,编译器告诉我不能。但是,我可以看到 DList 已经重载了该运算符。我错过了什么?

最佳答案

创建新容器的三种方式,

  1. 统一方式,使用std.container.make:

    auto list1 = make!(DList!int)();
    auto list2 = make!(DList!int)(1, 2);
  2. 使用结构初始化语法:

    auto list1 = DList!int();
  3. 使用类的辅助函数:

    auto tree1 = redBlackTree!int();
    auto tree2 = redBlackTree!int(1, 2);

它们之间的区别在于,一些数据结构是使用类实现的,而另一些是使用结构实现的。而使用 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`.

作为更完整的用法示例,请检查以下内容:

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

您可以在这里在线运行:http://dpaste.dzfl.pl/f34b2ec8a445

关于containers - D: 不清楚如何使用 std.container 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21643124/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com