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

C++ STL 算法精要(13):查找算法全解析與實戰範例

     編輯:關於C++

查找算法分類

算法用途複雜度備註
find查找單一值O(n)通用,線性掃描
find_if條件查找O(n)配合謂詞/函數對象
search_n查找 n 次重複值O(n*m)
search查找子序列O(n*m)
find_end查找子序列最後出現位置O(n*m)
find_first_of查找集合中任一元素首次出現O(n*m)
adjacent_find查找相鄰重複元素O(n)
binary_search有序區間二分查找O(log n)需有序
lower_bound首個不小於 value 位置O(log n)有序區間
upper_bound首個大於 value 位置O(log n)有序區間
equal_range等值範圍 [lower, upper)O(log n)有序區間

關鍵選擇原則

  1. 關聯式容器 (set/map 等) 自帶 find() 成員函數,紅黑樹實現 O(log n),優先使用。
  2. string 自帶 find(),優化過,優先使用。
  3. 已排序序列(vector、deque 等)使用 binary_search 族。
  4. 無序序列通用查找用 find/find_if。

實戰範例

1. find 多次查找同一值

list lst = {1,2,3,4,5,6,7,8, 1,2,3,4,5,6,7,8};
auto p1 = find(lst.begin(), lst.end(), 4);
auto p2 = (p1 != lst.end()) ? find(next(p1), lst.end(), 4) : lst.end();
if (p1 != lst.end() && p2 != lst.end()) {
    --p1; ++p2;
    for (auto it = p1; it != p2; ++it) cout << *it; // 輸出 3 4 5 6 7 8 1 2 3
}

2. find_if 配合函數對象與適配器

vector v = {1,2,3,4,5,6,7,8,9};
// 查找第一個 > 3 的元素
auto p = find_if(v.begin(), v.end(), bind2nd(greater(), 3)); // 輸出 4
// 查找第一個不能被 3 整除的元素
p = find_if(v.begin(), v.end(), not1(bind2nd(modulus(), 3))); // 輸出 1

現代 C++ (C++11+) 建議用 Lambda 替代 bind2nd/not1:

auto p = find_if(v.begin(), v.end(), [](int x){ return x > 3; });
auto p = find_if(v.begin(), v.end(), [](int x){ return x % 3 != 0; });

3. 關聯容器與 string 專用查找

set s = {43, 78, -1, 124}; // 自動排序
auto it = s.find(78); // O(log n),紅黑樹查找
if (it != s.end()) cout << "Found: " << *it;

string str = "AnnaBelle";
auto pos = str.find("Belle"); // 返回 3
if (pos != string::npos) cout << "Found at " << pos;

預定義函數對象速查

算術關係邏輯
plus<T>equal_to<T>logical_and<T>
minus<T>not_equal_to<T>logical_or<T>
multiplies<T>less<T>logical_not<T>
divides<T>greater<T>
modulus<T>less_equal<T>
negate<T>greater_equal<T>

適配器

  • bind1st(op, val) / bind2nd(op, val):綁定二元運算符一個參數。
  • not1(unary_pred) / not2(binary_pred):邏輯取反。
  • ptr_fun / mem_fun:函數指針/成員函數適配為函數對象。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved