c++ std標準庫 演算法<algorithm> for_each()仿函式用法
阿新 • • 發佈:2020-12-22
技術標籤:# 4.1 C++c++演算法for_each仿函式
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 初始化vect
template <class T>
void FillValue(T& vect, int first, int last)
{
if (last >= first)
{
for (int i = first; i <= last; ++i)
vect.insert (vect.end(), i);
}
else
{
cout << " The indexes is error: last < first. " << endl;
}
}
// 列印
void print(int elem)
{
cout << elem << " ";
}
// 仿函式
template <class T>
class Multiple {
private:
T theValue;
public:
Multiple(const T& v) : theValue (v)
{
}
void operator()(T& elem) const
{
elem *= theValue;
}
};
void main()
{
vector <int> myvector;
FillValue(myvector, 1, 10);
for_each(myvector.begin(), myvector.end(), print);
cout << endl;
for_each(myvector.begin(), myvector.end(), Multiple<int>(2));
for_each (myvector.begin(), myvector.end(), print);
cout << endl;
}