D语言关联数组

关联数组有一个索引,并不一定是一个整数。该指数的关联数组被称为键,它的类型就是所谓的关键字类型。

关联数组是通过将关键字类型的[]数组声明中声明。一个简单的例子为关联数组,如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import std.stdio;
void main ()
{
int[string] e; // associative array b of ints that are
e["test"] = 3;
writeln(e["test"]);
string[string] f;
f["test"] = "Tuts";
writeln(f["test"]);
writeln(f);
f.remove("test");
writeln(f);
}
当上面的代码被编译并执行,它会产生以下结果:
1
2
3
4
3
Tuts
["test":"Tuts"]
[]
初始化

关联数组的一个简单的初始化如下所示。

1
2
3
4
5
6
7
8
9
10
import std.stdio;
void main ()
{
int[string] days =
[ "Monday" : 0, "Tuesday" : 1, "Wednesday" : 2,
"Thursday" : 3, "Friday" : 4, "Saturday" : 5,
"Sunday" : 6 ];
writeln(days["Tuesday"]);
}
当上面的代码被编译并执行,它会产生以下结果:
1

属性

属性 描述
.sizeof 返回引用关联数组的大小;32位版本的4位,在64位版本为8位。
.length 返回关联数组中的值的数目。不同于动态数组,它是只读的。
.dup 创建相同大小的新关联数组和关联数组中的内容复制到其中。
.keys 返回动态数组,它的元素是关联数组中的键。
.values 返回动态数组,它的元素是关联数组中的值。
.rehash 重组的关联数组到位,使查找更高效。翻版时生效,例如,程序加载完成了一个符号表,现在需要快速查找它。返回一个引用到重组后的数组。
.byKey() 返回委托适合用作一个聚合到ForeachStatement这将遍历关联数组的键。
.byValue() 返回委托适合用作一个聚合到ForeachStatement这将遍历关联数组的值。
.get(Key key, lazy Value defVal) 查找键;如果存在相应的值则返回,否则求值,并返回defVal。
.remove(Key key) 删除一个对象的键。

利用上述特性,例如,如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import std.stdio;
void main ()
{
int[string] array1;
array1["test"] = 3;
array1["test2"] = 20;
writeln("sizeof: ",array1.sizeof);
writeln("length: ",array1.length);
writeln("dup: ",array1.dup);
array1.rehash;
writeln("rehashed: ",array1);
writeln("keys: ",array1.keys);
writeln("values: ",array1.values);
foreach (key; array1.byKey) {
writeln("by key: ",key);
}
foreach (value; array1.byValue) {
writeln("by value ",value);
}
writeln("get value for key test: ",array1.get("test",10));
writeln("get value for key test3: ",array1.get("test3",10));
array1.remove("test");
writeln(array1);
}
当上面的代码被编译并执行,它会产生以下结果:
sizeof: 8
length: 2
dup: ["test2":20, "test":3]
rehashed: ["test":3, "test2":20]
keys: ["test", "test2"]
values: [3, 20]
by key: test
by key: test2
by value 3
by value 20
get value for key test: 3
get value for key test3: 10
["test2":20]
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2024

备案号:京ICP备15003423号-3