| 算法 | 功能 |
is_sorted(first, last) | 判斷整個區間是否已排序(非遞減) |
is_sorted_until(first, last) | 返回指向**第一個破壞有序性**位置的迭代器(即最長有序前綴的末尾) |
代碼示例綜合
#include
#include
#include
#include // iota
using namespace std;
int main() {
vector v = {1,3,5,7,9,4};
auto isOdd = [](int x){ return x%2; };
cout << "all_of: " << all_of(v.begin(), v.end(), isOdd) << "\n"; // false
cout << "any_of: " << any_of(v.begin(), v.end(), [](int x){return x%2==0;}) << "\n"; // true
cout << "none_of: " << none_of(v.begin(), v.end(), [](int x){return x%2==0;}) << "\n"; // false
auto it = find_if_not(v.begin(), v.end(), isOdd); // 找第一個偶數
if (it != v.end()) cout << "first even: " << *it << "\n";
vector odds(v.size());
auto end = copy_if(v.begin(), v.end(), odds.begin(), isOdd);
odds.resize(distance(odds.begin(), end));
// odds = {1,3,5,7,9}
vector v2(4);
iota(v2.begin(), v2.end(), 1); // {1,2,3,4}
auto mm = minmax_element(v.begin(), v.end());
cout << "min=" << *mm.first << ", max=" << *mm.second << "\n";
auto pos = is_sorted_until(v.begin(), v.end());
for (auto it=v.begin(); it!=pos; ++it) cout << *it << ' '; // 1 3 5 7 9
cout << "\nis_sorted: " << is_sorted(v.begin(), v.end()) << "\n"; // 0
}
總結
C++11 算法庫新增項目針對常見模式(全量判斷、條件拷貝、序列生成、雙極值、有序檢查)提供標準化、可讀性強、性能優化的組件,配合 Lambda 表達式極大提升代碼表達力,建議優先使用而非手寫循環。
- 上一篇文章: C++ 語言體系設計哲學隨想:靜態類型、操作語義與零開銷抽象
- 下一篇文章: C/C++ 將無符號整型所有位置 1 的正確方法與常見誤區
Copyright ©
程式碼之家 All Rights Reserved