這是一個類似 C++ STL 的容器、迭代器和算法框架,迭代器的設計參考了 C++ boost 庫中的"new-style" 迭代器,把迭代器的遍歷和讀寫操作分開,內置數組處理參考了 qiezi 的文章: 仿STL的vector,寫了一組array操作方法。容器方法的命令沒有遵循 STL 的風格,而是采用 .Net 范型容器的名稱。
借助于 D 威力強大的模板和模板混入,代碼雖然大量用到了模板,但是十分地簡短易讀。
目前僅僅實現的部分包括:
- 雙向列表容器
- find & copy 算法(沒有模板特化的優化)
- 內置一維數組的迭代器
- 一個AOP模式的容器操作符重載
D 代碼
- module samples.base.collections;
- import dotmars.base.iterator;
- import dotmars.base.collection.list;
- import dotmars.base.collection.array;
- import dotmars.base.algorithms;
- import dotmars.io.console;
- void main()
- {
- alias List!(int) MyList;
- auto list = new MyList;
- list ~= 1; // this is equal to list.addList(1);
- list ~= 2;
- list ~= 3;
- list ~= 4;
- list ~= 5;
- list ~= 6;
- list.addFirst(7);
- //現在序列為: 7,1,2,3,4,5,6
- MyList.Iterator it = list.begin();
- ++it;
- ++it;
- //刪除2, it 指向3
- it = list.remove(it);
- //現在序列為: 7,2,3,4,5,6
- list.addBefore(it, 2); //在3之前插入2,it 指向 3
- int[] array;
- array.addLast(8); //內置數組也能享受到同樣的 addLast 成員函數
- array.addLast(9);
- // 內置數組也可以用迭代器訪問
- list.addRangeBefore(it, array.begin(), array.end()); //在3之前插入array的內容,即 8,9
- //使用 foreach 語句遍歷 list
- foreach(int i; list)
- Console.print("{0}, ", i);
- Console.newLine();
- //與 STL 類似,通過內部的迭代器反向遍歷 list
- for(MyList.ReverseIterator ri = list.rbegin(); ri != list.rend(); ++ri)
- Console.print("{0}, ", ri.current);
- Console.newLine();
- //調用通用算法
- MyList.Iterator pos = find(list.begin(), list.end(), 5);
- if(pos != list.end())
- Console.printLine("Pattern found: {0}", pos.current);
- list.clear();
- }
運行結果:
- 7, 1, 2, 9, 8, 3, 4, 5, 6,
- 6, 5, 4, 3, 8, 9, 2, 1, 7,
- Pattern found: 5
最新版程序可在 dotmars.googlecode.com/svn/trunk/samples/base/collections.d 處下載。
安徽新華電腦學校專業職業規劃師為你提供更多幫助【在線咨詢】