#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class A{
public:
A(){cout <<"A()"<<endl;}
~A(){cout <<"~A()"<<endl;}
void operator () (int &k)
{
cout <<k<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
{
vector<int> t(1,6);
for_each(t.begin(),t.end(),A());
}
system("pause");
return 0;
}
A()
6
~A()
~A()
~A()
~A()
请按任意键继续. . .
而下面代码的输出又不明白:
template<class T>
struct print : public unary_function<T, void>
{
print(ostream& out) : os(out), count(0) { cout << "print()"<<endl;}
~print(){cout << "~print()"<<endl;}
void operator() (T x) { os << x <<endl; ++count; }
ostream& os;
int count;
};
int main()
{
int A[] = {1, 4, 2, 8, 5, 7 ,22 ,99, 55 ,33,88};
const int N = sizeof(A) / sizeof(int);
print<int> P = for_each(A, A + N, print<int>(cout));
cout << endl << P.count << " objects printed." << endl;
system("pause");
}
输出结果为什么是下面的:
print()
1
4
2
8
5
7
22
99
55
33
88
~print()
~print()
~print()
11 objects printed.
请按任意键继续. . .