
在调用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 functionputs 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 elementtemplate<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.
总结以上是内存溢出为你收集整理的c – 使用for_each向量中每个元素的平方和全部内容,希望文章能够帮你解决c – 使用for_each向量中每个元素的平方和所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)