范圍是存取元素的抽象。這種抽象使得在容器類型的大量使用算法大量出現(xiàn)。范圍強調(diào)如何容器元素的訪問,而不是如何在容器中實現(xiàn)。范圍是一個是基于是否一個類型定義某組的成員函數(shù)非常簡單的概念。
D語言范圍片恰巧是最強大RandomAccessRange實現(xiàn)不可或缺的一部分,而且有很多的功能使用范圍。許多算法返回的臨時對象范圍。例如filter(),它選擇了大于10下面的代碼元素,實際上返回一個范圍對象,而不是一個數(shù)組:
數(shù)量范圍是相當常用的這些數(shù)字范圍是int類型。對于數(shù)量范圍的一些例子如下所示
// Example 1 foreach (value; 3..7) // Example 2 int[] slice = array[5..10];
關(guān)于結(jié)構(gòu)和類接口的范圍是福波斯的范圍。 Phobos是正式運行庫和標準庫自帶的D語言編譯器。
有多種類型的范圍,其中包括,
InputRange
ForwardRange
BidirectionalRange
RandomAccessRange
OutputRange
最簡單的范圍的輸入范圍。在其他范圍帶來他們是基于一系列的頂部更高的需求。有三個函數(shù)InputRange需求,
empty: 指定的范圍內(nèi)是否為空;當范圍被認為是空的,它必須返回true,否則返回false
front: 提供對元素的范圍的開始
popFront(): 通過去除所述第一元件從一開始就縮短了范圍
import std.stdio; import std.string; struct Student { string name; int number; string toString() const { return format("%s(%s)", name, number); } } struct School { Student[] students; } struct StudentRange { Student[] students; this(School school) { this.students = school.students; } @property bool empty() const { return students.length == 0; } @property ref Student front() { return students[0]; } void popFront() { students = students[1 .. $]; } } void main(){ auto school = School( [ Student("Raj", 1), Student("John", 2) , Student("Ram", 3) ] ); auto range = StudentRange(school); writeln(range); writeln(school.students.length); writeln(range.front); range.popFront; writeln(range.empty); writeln(range); }
當上面的代碼被編譯并執(zhí)行,它會產(chǎn)生以下結(jié)果:
[Raj(1), John(2), Ram(3)] 3 Raj(1) false [John(2), Ram(3)]
ForwardRange還需要保存成員函數(shù)部分來自其他三個功能InputRange和返回時保存函數(shù)被調(diào)用的范圍內(nèi)的一個副本。
import std.array; import std.stdio; import std.string; import std.range; struct FibonacciSeries { int first = 0; int second = 1; enum empty = false; // infinite range @property int front() const { return first; } void popFront() { int third = first + second; first = second; second = third; } @property FibonacciSeries save() const { return this; } } void report(T)(const dchar[] title, const ref T range) { writefln("%s: %s", title, range.上一篇:D語言常量下一篇:D語言并發(fā)