c – 使用for_each向量中每个元素的平方和
发布时间:2020-12-16 05:52:00 所属栏目:百科 来源:网络整理
导读:由于 for_each接受的功能只需要一个参数(矢量的元素),所以我必须在某处定义一个静态int sum = 0,以便可以访问 在调用for_each之后.我觉得这很尴尬任何更好的方式来做(仍然使用for_each)? #include algorithm#include vector#include iostreamusing namespac
由于
for_each接受的功能只需要一个参数(矢量的元素),所以我必须在某处定义一个静态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,4].each { |i| sum += i*i} #local variable can be used in the callback function puts sum #=> 30 你可以在实践编程中通常使用for_each(不只是打印每个元素)吗?是否可以使用for_each模拟“map”并将其注入到Ruby(或Haskell中的map / fold)中. #map in ruby >> [1,4].map {|i| i*i} => [1,4,9,16] #inject in ruby [1,16].inject(0) {|aac,i| aac +=i} #=> 30 编辑:谢谢大家我从你的答复中学到了很多东西.我们有很多方法在C中做同样的事情,这使得它有点难学.但这很有趣:) 解决方法
使用
std::accumulate
#include <vector> #include <numeric> // functor for getting sum of previous result and square of current element template<typename T> struct square { T operator()(const T& Left,const T& Right) const { return (Left + Right*Right); } }; void main() { std::vector <int> v1; v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); int x = std::accumulate( v1.begin(),v1.end(),square<int>() ); // 0 stands here for initial value to which each element is in turn combined with // for our case must be 0. } 您可以像nice GMan’s answer那样模拟std :: accumulate,但我相信使用std :: accumulate会使您的代码更易读,因为它是为这样的目的而设计的.你可以找到更多的标准算法here. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |