C++ 演算法庫 - for_each() 函式



描述

C++ 函式std::algorithm::for_each() 將提供的函式應用於範圍內的每個元素。

宣告

以下是來自 <algorithm> 標頭檔案的 std::algorithm::for_each() 函式宣告。

C++98

template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function fn);

引數

  • first − 輸入迭代器指向初始位置。

  • last − 結束迭代器指向最終位置。

  • fn − 一元函式,接受範圍內的元素作為引數。

返回值

返回函式fn.

異常

線性。

時間複雜度

如果函式fn或迭代器上的操作丟擲異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

示例

以下示例演示了 std::algorithm::for_each() 函式的用法。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int print_even(int n) {
   if (n % 2 == 0)
      cout << n << ' ';
}

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};

   cout << "Vector contains following even numebr" << endl;

   for_each(v.begin(), v.end(), print_even);

   cout << endl;

   return 0;
}

讓我們編譯並執行上面的程式,這將產生以下結果:

Vector contains following even numebr
2 4 
algorithm.htm
廣告