等价与哈希
Coddy 面向 C 开发者的 Dart 课程的第 40 课,共 48 课。
C 没有用于结构体的 == 运算符,也没有内置哈希表,因此哈希集合需要你编写并传入相等判断函数和哈希函数。用 memcmp 或指针相等来比较是一个经典 bug:它比较的是填充字节或地址,而不是成员指向的文本。对于 Set 和 Map 的键,Dart 的 == 和 hashCode 重写起到这些作用。相等的值必须有相同的哈希值,但哈希值相同并不能证明值相等。存储为键的字段应保持稳定。
相等的对象必须具有相同的 hashCode 值,但哈希冲突并不能证明对象相等。对象存储在哈希集合中时,与相等性相关的状态应保持稳定。
完整的 C 程序:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
struct tag {
const char *text;
};
static bool tag_equals(const struct tag *a, const struct tag *b) { return strcmp(a->text, b->text) == 0; }
static unsigned tag_hash(const struct tag *t) {
unsigned h = 5381;
for (const char *p = t->text; *p; p++) h = h * 33 + (unsigned char)*p;
return h;
}
struct tag_set {
struct tag items[8];
unsigned hashes[8];
int size;
};
static void tag_set_add(struct tag_set *s, struct tag t) {
unsigned h = tag_hash(&t);
for (int i = 0; i < s->size; i++)
if (s->hashes[i] == h && tag_equals(&s->items[i], &t)) return;
s->items[s->size] = t;
s->hashes[s->size++] = h;
}
int main(void) {
char first[] = "a", second[] = "a"; /* 两个地址中的文本相同 */
struct tag_set s = {0};
tag_set_add(&s, (struct tag){first});
tag_set_add(&s, (struct tag){second});
printf("%d\n", s.size);
return 0;
}
完整的 Dart 程序:
class Tag{final String text;const Tag(this.text);@override bool operator ==(Object other)=>other is Tag&&text==other.text;@override int get hashCode=>text.hashCode;}
void main(){print({Tag('a'),Tag('a')}.length);}挑战
简单实现不可变的 Key(int row,int column),并包含 final 公共字段。当且仅当两个坐标都相同时,两个 Key 才相等。以一致的方式重写 operator == 和 hashCode。输入由完整的整数坐标对组成。使用 Set 统计不同的键,并返回数量。坐标范围为 -100 到 100。
不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立检查公共 API,并在结果后输出一个换行符。
你的代码应写在 Key.dart 和 exercise.dart 中。main.dart 包含提供的输入输出代码,不能编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Key.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final a=Key(2,3),b=Key(2,3);check(a==b && a.hashCode==b.hashCode && a!=Key(3,2));check({a,b}.length==1);
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Dart中的所有课
自己练习: Dart 在线编译器