日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

函数对象应用

發(fā)布時(shí)間:2025/3/12 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 函数对象应用 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

計(jì)算幾個(gè)數(shù)的n次方和

#include<iostream> #include<vector> #include<algorithm> #include<numeric> #include<functional> using namespace std; int sumsquares(int total, int value) {return total+value*value; }template<class T>//模板 void printinterval(T first,T last) {//輸出區(qū)間[first,last)中的元素 for(;first!=last;++first)cout<<*first<<" ";cout<<endl; } template<class T>//類(lèi)模板 class sumpowers//求區(qū)間多少次方的和 {private:int power; public:sumpowers(int p):power(p){}const T operator()(const T &total,const T &value){//計(jì)算value的power次方,加到total上 T v=value;for(int i=0;i<power-1;++i)//v乘power-1次 v=v*value;return total + v;} } ; int main() {const int sze =10;int a1[]={1,2,3,4,5,6,7,8,9,10};vector<int>v(a1,a1+sze);//用a1數(shù)組初始化v cout<<"1)";printinterval(v.begin(),v.end());int result = accumulate(v.begin(),v.end(),0,sumsquares);cout<<"2)平方和: "<<result<<endl;result=accumulate(v.begin(),v.end(),0,sumpowers<int>(3));cout<<"3)立方和: "<<result<<endl;result= accumulate(v.begin(),v.end(),0,sumpowers<int>(4));cout<<"4)4次方和: "<<result;return 0;/**1)1 2 3 4 5 6 7 8 9 102)平方和: 3853)立方和: 30254)4次方和: 25333**/ }

分析一下accumulate

int result = accumulate(v.begin,v.end(),0,sumsquares);int accumulate(vector<int>::iterator first,vector<int>::iterator last,int init,int(*op)(int,int))//與函數(shù)名相匹配,函數(shù)指針 {for( ;first!=lats;++first)init =op(init,*first);//調(diào)用sumsquares return init; }int result = accumulate(v.begin,v.end(),0,sumpowers<int>(3));//op的powe成員變量是3 op是一個(gè)函數(shù)對(duì)象 int accumulate(vector<int>::iterator first,vector<int>::iterator last,int init,sumpowers<int>op ) {for( ;first!=lats;++first)init =op(init,*first);//調(diào)用()并把power初始化為三 return init; }accumulate(vector<int>::iterator first,vector<int>::iterator last,int init,binaryop)//binaryop對(duì)應(yīng)的實(shí)參可以使函數(shù)名,函數(shù)指針 ,函數(shù)對(duì)象

好處

如果沒(méi)有函數(shù)對(duì)象,那求不同的立方和都要寫(xiě)一個(gè)函數(shù),或者定義一個(gè)全局變量,但這樣獨(dú)立性不好,而函數(shù)對(duì)象完美解決這個(gè)問(wèn)題

總結(jié)

以上是生活随笔為你收集整理的函数对象应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。