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

C++ STL any_of 算法詳解與使用示例

     編輯:C++ 入門

函數原型

template <class InputIterator, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);

功能說明

若區間 [first, last) 中任意元素滿足一元謂詞 pred(即 pred(elem) == true),返回 true;否則返回 false。空區間直接返回 false。

等價實現

template <class InputIterator, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred) {
    while (first != last) {
        if (pred(*first)) return true;
        ++first;
    }
    return false;
}

使用示例 1:基本用法

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool isGreat(int i) {
    if (i >= 5) {
        cout << i << " >= 5, match!" << endl;
        return true;
    }
    return false;
}

int main() {
    vector<int> vi = {0,1,2,3,4,5,6};
    if (any_of(vi.begin(), vi.end(), isGreat))
        cout << "yes, some elements in vi >= 5" << endl;
    else
        cout << "all elements in vi < 5" << endl;
    return 0;
}

輸出:

5 >= 5, match!
6 >= 5, match!
yes, some elements in vi >= 5

使用示例 2:空區間

vector<int> vi = {0,1,2,3,4,5,6};
if (any_of(vi.begin(), vi.begin(), isGreat))
    cout << "emptiy = true" << endl;
else
    cout << "emptiy = false" << endl;
// 輸出: emptiy = false

配合 Lambda 表達式 (C++11)

vector<int> v = {1, 3, 5, 7, 9};
bool hasEven = any_of(v.begin(), v.end(), [](int x){ return x % 2 == 0; });
// hasEven == false

注意事項

  • 短路求值:找到第一個滿足條件的元素即返回,不遍歷剩餘元素。
  • 謂詞可為函數指針、函數對象、Lambda。
  • 頭文件:<algorithm> (C++11 起)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved