【发布时间】:2009-08-25 04:50:51
【问题描述】:
由于for_each接受的函数只有一个参数(向量的元素),所以我必须在某处定义一个static int sum = 0,以便可以访问它
在调用 for_each 之后。我觉得这很尴尬。有没有更好的方法来做到这一点(仍然使用 for_each)?
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
static int sum = 0;
void add_f(int i )
{
sum += i * i;
}
void test_using_for_each()
{
int arr[] = {1,2,3,4};
vector<int> a (arr ,arr + sizeof(arr)/sizeof(arr[0]));
for_each( a.begin(),a.end(), add_f);
cout << "sum of the square of the element is " << sum << endl;
}
在 Ruby 中,我们可以这样做:
sum = 0
[1,2,3,4].each { |i| sum += i*i} #local variable can be used in the callback function
puts sum #=> 30
能否请您展示更多示例for_each 通常如何用于实际编程(不仅仅是打印出每个元素)? 是否可以使用for_each 模拟“编程模式”,如地图和在 Ruby 中注入(或在 Haskell 中映射 /fold)。
#map in ruby
>> [1,2,3,4].map {|i| i*i}
=> [1, 4, 9, 16]
#inject in ruby
[1, 4, 9, 16].inject(0) {|aac ,i| aac +=i} #=> 30
编辑:谢谢大家。我从你的回复中学到了很多。我们有很多方法可以在 C++ 中做同样的事情,这使得学习有点困难。但这很有趣:)
【问题讨论】:
标签: c++ vector stl-algorithm