STL之for_each

getline 2008-05-20 10:30:10
简单说就是把容器里的每个元素加上一个值。实现如下:

#include <iostream>
#include <list>
#include <algorithm>
#include <functional>
using namespace std;

class AddValue
{
public:
AddValue(int v) : theValue(v) {}
void operator() (int& elem) const
{
elem += theValue;
}
private:
int theValue;
};

int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
list<int> ilst(a, a+sizeof(a)/sizeof(a[0]));

for_each (ilst.begin(), ilst.end(), AddValue(10));

for (list<int>::iterator iter = ilst.begin(); iter != ilst.end(); iter++)
cout << *iter << " ";

return 0;
}

没问题。后来想用标准里现成的来实现。
把for_each (ilst.begin(), ilst.end(), AddValue(10));改为:
for_each (ilst.begin(), ilst.end(), bind2nd(plus<int>(), 10));
运行后发现并没有改变。Why?????

这样是可以的transform (ilst.begin(), ilst.end(), ilst.begin(), bind2nd(plus<int>(), 10));
...全文
114 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
getline 2008-05-20
  • 打赏
  • 举报
回复
template<class _Ty>
struct plus : binary_function<_Ty, _Ty, _Ty> {
_Ty operator()(const _Ty& _X, const _Ty& _Y) const
{return (_X + _Y); }
};

看了下参数带是引用的,返回的不是引用。 知道是怎么回事了,谢谢你!
hastings 2008-05-20
  • 打赏
  • 举报
回复
plus的参数不是引用类型.

64,691

社区成员

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

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