首页 新闻 会员 周边

关于函数对象的问题

0
悬赏园豆:10 [已解决问题] 解决于 2011-12-28 13:22
 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是说没有析构函数啊?

 

林羽飞扬的主页 林羽飞扬 | 初学一级 | 园豆:193
提问于:2011-12-26 14:22
< >
分享
最佳答案
0
1     struct Show<int> show;
2 show.operator()(100);

您要指定一个模版参数啊。

for_each 参看: http://www.cplusplus.com/reference/algorithm/for_each/

收获园豆:10
ChatinCode | 老鸟四级 |园豆:2272 | 2011-12-26 16:21
其他回答(3)
0

应该要添加一个Show的构造函数,当时我还在C语言那种结构体纠结,原理C++的结构体已经添加了很多东西了

林羽飞扬 | 园豆:193 (初学一级) | 2011-12-26 15:03
0
for_each方法是怎么写的?
artwl | 园豆:16736 (专家六级) | 2011-12-26 16:13

for_each是

#include <algorithm>这algorithm所定义的通用函数
支持(0) 反对(0) 林羽飞扬 | 园豆:193 (初学一级) | 2011-12-28 12:58
0
// 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;
}
Rollen Holt | 园豆:210 (菜鸟二级) | 2012-03-21 16:24
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册