为什么for_each这样不能通过编译

yeyunxiaopan 2007-06-01 10:27:45
#include <afx.h>
#include <iostream.h>
#include <list>
#include <algorithm>

using namespace std;

typedef list<int> int_List;
class A
{

void PrintInt(int n)
{
cout<<n<<endl;

}

void test()
{
int_List nList;

nList.push_back(1);
nList.push_back(2);
nList.push_back(3);
nList.push_back(4);

for_each(nList.begin(),nList.end(),PrintInt);

}

};
void main()
{


}

错误提示
error C2664: 'for_each' : cannot convert parameter 3 from 'void (int)' to 'void (__thiscall *)(int)'
...全文
343 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
这样写
for_each(nList.begin(),nList.end()
,bind1st( mem_fun(&A::PrintInt),this)
);
mimong_lin 2007-06-01
  • 打赏
  • 举报
回复
void PrintInt(list<int>:: iterator p)
{
cout<<*p<<endl;

}
xfan_hsl 2007-06-01
  • 打赏
  • 举报
回复
必须注意一点:for_each()中的函数地址必须是在编译能确定的,所以建议---PrintInt为静态函数

另外,多注意下面的区别:
user-defined generic function
Function as algorithm arguments
Predicate(unary, binary)
Function object

我个人理解是:
1 Suppose you want to add a certain value to all elements of a collection. If you know the value you want to add at compile time, you could use an ordinary function
2 If you need different values that are known at compile time, you could use a
template instead
3 If you need such a function twice, with two different values to add, and both values are processed at runtime, you could use a function objects instead
taodm 2007-06-01
  • 打赏
  • 举报
回复
VC6就不讨论了。建议你尽早扔了,换VC2005或者devcpp。
用VC6学C++就是浪费生命。
yeyunxiaopan 2007-06-01
  • 打赏
  • 举报
回复
是VC6啊,编译器不支持吗?
taodm 2007-06-01
  • 打赏
  • 举报
回复
楼主什么编译器?不会又是VC6吧?
devcpp下编译通过。
yeyunxiaopan 2007-06-01
  • 打赏
  • 举报
回复
不好意思,好像还是不行啊

用三楼的方法,错误跟我开始一样

用四楼的方法,错误是 error C2784: 'class std::mem_fun_t<_R,_Ty> __cdecl std::mem_fun(_R (__thiscall _Ty::*)(void))' : could not deduce template argument for '<Unknown>' from 'void (__thiscall A::*)(int)'
  • 打赏
  • 举报
回复
因为PrintInt是成员函数,所以需要将这个函数进行转化成普通的函数.
yeyunxiaopan 2007-06-01
  • 打赏
  • 举报
回复
非常感谢,请问楼上的为什么要这样写呢

65,208

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧