函式模板
<algorithm>

std::for_each

template <class InputIterator, class Function>   Function for_each (InputIterator first, InputIterator last, Function fn);
將函式應用於範圍
將函式 fn 應用於範圍 [first,last) 中的每個元素。

此模板函式的行為等效於
1
2
3
4
5
6
7
8
9
template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function fn)
{
  while (first!=last) {
    fn (*first);
    ++first;
  }
  return fn;      // or, since C++11: return move(fn);
}

引數

first, last
輸入迭代器 到序列的起始和結束位置。使用的範圍是 [first,last),它包含 first 和 last 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
fn
一元函式,接受範圍中的元素作為引數。
這可以是指標函式或 可移動構造 的函式物件。
它的返回值(如果有)將被忽略。

返回值

返回 fn
返回 fn,如同呼叫 std::move(fn)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// for_each example
#include <iostream>     // std::cout
#include <algorithm>    // std::for_each
#include <vector>       // std::vector

void myfunction (int i) {  // function:
  std::cout << ' ' << i;
}

struct myclass {           // function object type:
  void operator() (int i) {std::cout << ' ' << i;}
} myobject;

int main () {
  std::vector<int> myvector;
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(30);

  std::cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myfunction);
  std::cout << '\n';

  // or:
  std::cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myobject);
  std::cout << '\n';

  return 0;
}

輸出
myvector contains: 10 20 30
myvector contains: 10 20 30


複雜度

線性於 firstlast 之間的 距離:將 fn 應用於每個元素。

資料競爭

範圍 [first,last) 中的物件將被訪問(每個物件恰好訪問一次)。
如果 InputIterator可變迭代器型別且 fn 不是常量函式,則可以修改這些物件。

異常

如果 fn 引發異常,或者迭代器上的任何操作引發異常,則丟擲異常。
請注意,無效引數會導致未定義行為

另見