for_each 源码剖析

一:用法解析
函数原型:

template
   Function for_each (InputIterator first, InputIterator last, Function fn);

功能:

对[ first , last )范围内的元素执行Function操作。

例子:

// for_each example
#include      // std::cout
#include     // std::for_each
#include        // 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 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

二:源码剖析
// TEMPLATE FUNCTION for_each
template inline
	void _For_each(_InIt _First, _InIt _Last, _Fn1& _Func)
	{	// perform function for each element
	for (; _First != _Last; ++_First)
		_Func(*_First);
	}

template inline
	_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
	{	// perform function for each element
	_DEBUG_RANGE_PTR(_First, _Last, _Func);
	_For_each(_Unchecked(_First), _Unchecked(_Last), _Func);

	return (_STD move(_Func));
	}




源码摘抄自Visual Studio 2015安装目录algorithm文件中。



点击进入目录----> C++源码剖析目录




你可能感兴趣的:(<专栏>,--C++,源码剖析)