国产一区二区精品久久_蜜桃狠狠狠狠狠狠狠狠狠_午夜视频精品_激情都市一区二区

當前位置:首頁 > 網站舊欄目 > 學習園地 > 設計軟件教程 > Dotmars 實例之:容器、迭代器與算法框架

Dotmars 實例之:容器、迭代器與算法框架
2010-01-13 22:50:44  作者:  來源:
這幾天 Mr. Bright 老是不放新版本,圈子里太冷清了,我來發篇程序湊個數。

這是一個類似 C++ STL 的容器、迭代器和算法框架,迭代器的設計參考了 C++ boost 庫中的"new-style" 迭代器,把迭代器的遍歷和讀寫操作分開,內置數組處理參考了 qiezi 的文章: 仿STL的vector,寫了一組array操作方法。容器方法的命令沒有遵循 STL 的風格,而是采用 .Net 范型容器的名稱。

借助于 D 威力強大的模板和模板混入,代碼雖然大量用到了模板,但是十分地簡短易讀。

目前僅僅實現的部分包括:
  • 雙向列表容器
  • find & copy 算法(沒有模板特化的優化)
  • 內置一維數組的迭代器
  • 一個AOP模式的容器操作符重載
廢話少說,看看范例程序展現的威力:

D 代碼
 
  1. module samples.base.collections;
  2.  
  3. import dotmars.base.iterator;
  4. import dotmars.base.collection.list;
  5. import dotmars.base.collection.array;
  6. import dotmars.base.algorithms;
  7. import dotmars.io.console;
  8.  
  9. void main()
  10. {
  11. alias List!(int) MyList;
  12.  
  13. auto list = new MyList;
  14.  
  15. list ~= 1; // this is equal to list.addList(1);
  16. list ~= 2;
  17. list ~= 3;
  18. list ~= 4;
  19. list ~= 5;
  20. list ~= 6;
  21. list.addFirst(7);
  22.  
  23. //現在序列為: 7,1,2,3,4,5,6
  24.  
  25. MyList.Iterator it = list.begin();
  26. ++it;
  27. ++it;
  28.  
  29. //刪除2, it 指向3
  30. it = list.remove(it);
  31.  
  32. //現在序列為: 7,2,3,4,5,6
  33.  
  34. list.addBefore(it, 2); //在3之前插入2,it 指向 3
  35.  
  36.  
  37. int[] array;
  38. array.addLast(8); //內置數組也能享受到同樣的 addLast 成員函數
  39. array.addLast(9);
  40.  
  41. // 內置數組也可以用迭代器訪問
  42. list.addRangeBefore(it, array.begin(), array.end()); //在3之前插入array的內容,即 8,9
  43.  
  44. //使用 foreach 語句遍歷 list
  45. foreach(int i; list)
  46. Console.print("{0}, ", i);
  47.  
  48. Console.newLine();
  49.  
  50. //與 STL 類似,通過內部的迭代器反向遍歷 list
  51. for(MyList.ReverseIterator ri = list.rbegin(); ri != list.rend(); ++ri)
  52. Console.print("{0}, ", ri.current);
  53.  
  54. Console.newLine();
  55.  
  56. //調用通用算法
  57. MyList.Iterator pos = find(list.begin(), list.end(), 5);
  58.  
  59. if(pos != list.end())
  60. Console.printLine("Pattern found: {0}", pos.current);
  61.  
  62. list.clear();
  63. }

運行結果:
  1. 7, 1, 2, 9, 8, 3, 4, 5, 6,
  2. 6, 5, 4, 3, 8, 9, 2, 1, 7,
  3. Pattern found: 5


最新版程序可在 dotmars.googlecode.com/svn/trunk/samples/base/collections.d 處下載。


安徽新華電腦學校專業職業規劃師為你提供更多幫助【在線咨詢