首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

避免重複造輪子——善用標準庫(續三):C++ STL、F#、Ruby 排序寫法對比

     編輯:關於C語言

C++0x Lambda 與 Range-based for (VS2010 CTP)

// Lambda 寫法排序
sort(v.begin(), v.end(), [](const Person& p1, const Person& p2) {
    if (p1.num != p2.num) return p1.num < p2.num;
    return p1.name < p2.name;
});
// Range-based for 迭代 (C++11 標準)
for (Person p : v) cout << "Person: " << p.num << ", " << p.name << endl;

註:VS2010 CTP 支援 Lambda,但 Range-based for 尚未實作 (需 Concept 支援)。

F# 簡潔表達

let l = [(2, "smith"); (1, "john"); (2, "micheal"); (1, "micheal"); (3, "albert")]
List.sort compare l
// 結果:[(1, "john"); (1, "micheal"); (2, "micheal"); (2, "smith"); (3, "albert")]

Tuple 自動提供字典序比較,List.sort compare 一行完成。

Ruby 陣列排序

l = [[2, "smith"], [1, "john"], [2, "micheal"], [1, "micheal"], [3, "albert"]]
l.sort
// => [[1, "john"], [1, "micheal"], [2, "micheal"], [2, "smith"], [3, "albert"]]

陣列預設逐元素比較,符合直覺。

結論

腳本/函數式語言內建高階抽象,排序等常見操作極度簡潔。C++ 依賴 STL 與現代標準 (C++11/14/17) 逐步縮小差距。核心觀念:**善用標準庫/內建函數,勿手寫演算法**。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved