// 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 支援)。
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 一行完成。
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) 逐步縮小差距。核心觀念:**善用標準庫/內建函數,勿手寫演算法**。