1 #include <iostream>
2 #include <algorithm>
3 using namespace std;
4 template <typename T>
5 struct Show
6 {
7 void operator()(const T& element) const
8 {
9 cout<<element<<endl;
10 }
11 };
12 int main()
13 {
14
15 int a[3]={1,2,3};
16 for_each(a,a+3,Show<int>());
17
18 int n;
19 cin>>n;
20 return 0;
21 }
这里结构体Show是如何接受参数的啊如何运行的啊?
还有为什么我struct Show show是说没有析构函数啊?
1 struct Show<int> show;
2 show.operator()(100);
您要指定一个模版参数啊。
for_each 参看: http://www.cplusplus.com/reference/algorithm/for_each/
应该要添加一个Show的构造函数,当时我还在C语言那种结构体纠结,原理C++的结构体已经添加了很多东西了
for_each方法是怎么写的?
for_each是
#include <algorithm>这algorithm所定义的通用函数
// for_each example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void myfunction (int i) {
cout << "" << i;
}
struct myclass {
void operator() (int i) {cout << "" << i;}
} myobject;
int main () {
vector<int> myvector;
myvector.push_back(10);
myvector.push_back(20);
myvector.push_back(30);
cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myfunction);
// or:
cout << "\nmyvector contains:";
for_each (myvector.begin(), myvector.end(), myobject);
cout << endl;
return 0;
}