范圍是存取元素的抽象。這種抽象使得在容器類(lèi)型的大量使用算法大量出現(xiàn)。范圍強(qiáng)調(diào)如何容器元素的訪問(wèn),而不是如何在容器中實(shí)現(xiàn)。范圍是一個(gè)是基于是否一個(gè)類(lèi)型定義某組的成員函數(shù)非常簡(jiǎn)單的概念。
D語(yǔ)言范圍片恰巧是最強(qiáng)大RandomAccessRange實(shí)現(xiàn)不可或缺的一部分,而且有很多的功能使用范圍。許多算法返回的臨時(shí)對(duì)象范圍。例如filter(),它選擇了大于10下面的代碼元素,實(shí)際上返回一個(gè)范圍對(duì)象,而不是一個(gè)數(shù)組:
數(shù)量范圍是相當(dāng)常用的這些數(shù)字范圍是int類(lèi)型。對(duì)于數(shù)量范圍的一些例子如下所示
// Example 1 foreach (value; 3..7) // Example 2 int[] slice = array[5..10];
關(guān)于結(jié)構(gòu)和類(lèi)接口的范圍是福波斯的范圍。 Phobos是正式運(yùn)行庫(kù)和標(biāo)準(zhǔn)庫(kù)自帶的D語(yǔ)言編譯器。
有多種類(lèi)型的范圍,其中包括,
InputRange
ForwardRange
BidirectionalRange
RandomAccessRange
OutputRange
最簡(jiǎn)單的范圍的輸入范圍。在其他范圍帶來(lái)他們是基于一系列的頂部更高的需求。有三個(gè)函數(shù)InputRange需求,
empty: 指定的范圍內(nèi)是否為空;當(dāng)范圍被認(rèn)為是空的,它必須返回true,否則返回false
front: 提供對(duì)元素的范圍的開(kāi)始
popFront(): 通過(guò)去除所述第一元件從一開(kāi)始就縮短了范圍
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); }
當(dāng)上面的代碼被編譯并執(zhí)行,它會(huì)產(chǎn)生以下結(jié)果:
[Raj(1), John(2), Ram(3)] 3 Raj(1) false [John(2), Ram(3)]
ForwardRange還需要保存成員函數(shù)部分來(lái)自其他三個(gè)功能InputRange和返回時(shí)保存函數(shù)被調(diào)用的范圍內(nèi)的一個(gè)副本。
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語(yǔ)言常量下一篇:D語(yǔ)言并發(fā)