D语言实现映射数据结构 (Map) - 示例与代码
D语言没有直接提供的映射数据结构,但可以使用数组、结构体或类来实现映射功能。以下是一种基于结构体的简单映射实现的示例:
struct KeyValuePair(K, V) {
K key;
V value;
}
struct Map(K, V) {
private KeyValuePair!(K, V)[] items;
void put(K key, V value) {
foreach (ref item; items) {
if (item.key == key) {
item.value = value;
return;
}
}
items ~= KeyValuePair!(K, V)(key, value);
}
V get(K key) {
foreach (item; items) {
if (item.key == key) {
return item.value;
}
}
return V.init; // 返回默认值 if key not found
}
bool contains(K key) {
foreach (item; items) {
if (item.key == key) {
return true;
}
}
return false;
}
void remove(K key) {
foreach (i, ref item; items) {
if (item.key == key) {
items = items[0..i] ~ items[i + 1..$];
return;
}
}
}
}
void main() {
Map!(string, int) map;
map.put("one", 1);
map.put("two", 2);
writeln(map.get("one")); // 输出: 1
writeln(map.get("two")); // 输出: 2
writeln(map.contains("two")); // 输出: true
map.remove("one");
writeln(map.get("one")); // 输出: 0 (默认值)
}
以上示例使用KeyValuePair结构体表示键值对,Map结构体通过存储KeyValuePair的数组来实现映射功能,并提供了put、get、contains和remove等方法来操作映射。
原文地址: https://www.cveoy.top/t/topic/pKfW 著作权归作者所有。请勿转载和采集!