我想保留一组有序的记录,标准为我提供了 RedBlackTree。记录的类型是 Tuple!(string, uint)。这是它的样子:
import std.json : parseJSON;
uint[string] wordTable;
import std.datetime.stopwatch : StopWatch, AutoStart;
auto sw = StopWatch(AutoStart.yes);
const auto j = parseJSON(get(link));
const long downloadTime = sw.peek.total!"msecs";
import std.typecons : Tuple, tuple;
import std.container.rbtree : RedBlackTree;
import std.functional : binaryFun;
RedBlackTree!(Tuple!(string, uint), binaryFun!("a[1] > b[1]")) records;
foreach (node; j["posts"].array()) {
import std.stdio : writeln;
import std.utf : decode;
if ("com" in node) {
import std.algorithm : splitter;
foreach (word; getStr(node["com"].str()).splitter(' ')) {
import std.string : strip;
if (word.strip().length > 0)
wordTable.require(word, 0)++;
records ~= (tuple(word, wordTable[word])); // error
}
}
}
现在主要是我使用insert()
方法将记录添加到记录中,但它会导致运行时出现段错误。所以我决定使用 ~= 希望得到更好的错误信息。这是编译器所说的:
错误:不能将类型 Tuple!(string, uint) 附加到类型 std.container.rbtree.RedBlackTree!(Tuple!(string, uint), binaryFun, false)
根据https://dlang.org/phobos/std_container_rbtree.html#.RedBlackTree我必须提供一种类型,以便调用less(a, b)
它返回一个布尔值。所以我继续为它创建了一个类型:
struct Record {
string key;
uint value;
int opCmp(ref const Record other) const {
return value - other.value;
}
}
// bool less(Record a, Record b) {
// return a < b;
// }
void main(string[] args) {
import std.stdio : writeln, writefln;
if (args.length < 3) {
writeln("Must have 2 arguments " ~ "first argument is the link, "
~ "the second one is for minimum repeatation threshold. Exiting.");
import core.stdc.stdlib : exit;
exit(-1);
}
const auto link = parseLink(args[1]);
const auto threshold = atoui(args[2]);
import std.json : parseJSON;
uint[string] wordTable;
import std.datetime.stopwatch : StopWatch, AutoStart;
auto sw = StopWatch(AutoStart.yes);
const auto j = parseJSON(get(link));
const long downloadTime = sw.peek.total!"msecs";
import std.container.rbtree : RedBlackTree;
import std.functional : binaryFun;
RedBlackTree!Record records;
foreach (node; j["posts"].array()) {
import std.utf : decode;
if ("com" in node) {
import std.algorithm : splitter;
foreach (word; getStr(node["com"].str()).splitter(' ')) {
import std.string : strip;
if (word.strip().length > 0)
wordTable.require(word, 0)++;
records ~= (Record(word, wordTable[word]));
}
}
}
这次编译器抱怨:
错误:无法将类型记录附加到类型 std.container.rbtree.RedBlackTree!(记录,“a < b”,false)
所以问题的要点是,如果我有一个带有 custom 的 RedBlackTree,binaryFun
我如何向它添加元组或自定义类型的实例?