Dlang 语言 opApply 重载:迭代数组、范围等数据结构
Dlang 语言中,'opApply' 是一种重载运算符,它可以用来迭代数组、范围等数据结构。'opApply' 的基本用法如下:
struct MyArray {
int[] data;
void opApply(scope void delegate(ref int) apply) {
foreach(ref item; data) {
apply(item);
}
}
}
void main() {
MyArray arr = MyArray([1, 2, 3]);
foreach(item; arr) {
writeln(item);
}
}
在上面的代码中,MyArray 结构体重载了 'opApply' 运算符,用来迭代 'data' 数组中的元素。'opApply' 函数接受一个 'void delegate(ref int)' 类型的参数 'apply',用来处理每个数组元素。在 'main' 函数中,我们可以使用 'foreach' 循环来遍历 MyArray 对象 'arr' 中的元素。
除了迭代数组,'opApply' 还可以用来迭代其他数据结构,比如范围。下面是一个使用 'opApply' 迭代范围的例子:
struct MyRange {
int start;
int end;
void opApply(scope void delegate(ref int) apply) {
for(int i = start; i < end; i++) {
apply(i);
}
}
}
void main() {
MyRange r = MyRange(1, 5);
foreach(i; r) {
writeln(i);
}
}
在上面的代码中,MyRange 结构体重载了 'opApply' 运算符,用来迭代 '[start, end)' 范围中的整数。我们可以使用 'foreach' 循环来遍历 MyRange 对象 'r' 中的元素。
原文地址: http://www.cveoy.top/t/topic/olg7 著作权归作者所有。请勿转载和采集!