當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Algorithm for_each()用法及代碼示例


描述

C++ 函數std::algorithm::for_each()在範圍的每個元素上應用提供的函數。

聲明

以下是 std::algorithm::for_each() 函數形式 std::algorithm 頭文件的聲明。

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 

相關用法


注:本文由純淨天空篩選整理自 C++ Algorithm Library - for_each() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。