溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++函數(shù)對象如何理解

發(fā)布時間:2021-11-29 15:21:43 來源:億速云 閱讀:108 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容主要講解“C++函數(shù)對象如何理解”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“C++函數(shù)對象如何理解”吧!

1.函數(shù)對象與謂詞

概念上,函數(shù)對象是用作函數(shù)的對象;實現(xiàn)上,函數(shù)對象是實現(xiàn)operator()類的對象。
其實函數(shù)和函數(shù)指針都屬于函數(shù)對象,但是實現(xiàn)了operator()的類的對象才能保存類的成員屬性的值,才能用于標(biāo)準(zhǔn)模板庫(STL)算法。
常用于STL算法的函數(shù)對象有以下兩種類型:
一元函數(shù):接受一個參數(shù)的函數(shù),如f(x)。如果該函數(shù)返回一個布爾值,則該函數(shù)為謂詞。
二元函數(shù):接受兩個參數(shù)的函數(shù),如f(x,y)。如果該函數(shù)返回一個布爾值,則該函數(shù)成為二元謂詞。

2.函數(shù)對象的典型用途

通過下面程序理解函數(shù)對象的工作原理:
一元函數(shù):

#include<algorithm>#include<iostream>#include<vector>#include<list>using namespace std;template<typename elementType>struct DisplayElement{
   
   
   
  void operator()(const elementType& element)const
  {
   
   
     cout<<element<<">;
  }};int main(){
   
   
   
   vector <int> vecIntegers;
   for(int count=0;count<10;++count)vecIntegers.push_back(count);
   	list<char>listChars;
   	for(char nchar='a';nchar<'K';++nchar)
   		listChars.push_back(nchar);
   	cout<<"顯示整型動態(tài)數(shù)組:"<<endl;
   	foe_each(vecIntegers.begin(),vecIntegers.end(),DisplayElement<int>());//函數(shù)對象用于了STL算法std::for_each
   	cout<<"顯示字符動態(tài)數(shù)組:"<<endl;
   	for_each(listChars.begin(),listChars.end(),DisplayElement<char>());
   	return 0;}```

二元函數(shù):
如何在STL std::transform中使用該二元函數(shù):

#include<vector>#include<iostream>#include<algorithm>using namespace std;template<typename elementType>class Multiply{
   
   
   
	elementType operator()(const elementType& elem1, const elementType& elem2){
   
   
   return (elem1*elem2);}};int main(){
   
   
   
	vector<int>vecMultiplicand,vecMultiplier;for(int nCount=0;nCount<10;++nCount)
		vecMultiplicand.push_back(nCount);for(int nCount2=100;nCount2<110;++nCount2)
		vecMultiplier.push_back(nCount);
	vector<int>vecResult;
	vecResult.resize(10);transform(vecMultiplicand.begin(),vecMultiplicand.end(),vecMultiplier.begin(),vecResult.begin(),Multiply<int>());cout<<"The result of the multiplication is: "<<endl;for(size_t Index=0;Index<vecResult.size();++Index)	cout<<vecResult[Index]<<' ';return 0;}

到此,相信大家對“C++函數(shù)對象如何理解”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI