1.述語関数オブジェクト
概念上,函数对象是用作函数的对象;实现上,函数对象是实现operator()类的对象。
其实函数和函数指针都属于函数对象,但是实现了operator()的类的对象才能保存类的成员属性的值,才能用于标准模板库(STL)算法。
常用于STL算法的函数对象有以下两种类型:
一元函数:接受一个参数的函数,如f(x)。如果该函数返回一个布尔值,则该函数为谓词。
二元函数:接受两个参数的函数,如f(x,y)。如果该函数返回一个布尔值,则该函数成为二元谓词。
2.典型的な用途は、オブジェクト機能します
プログラムの動作を以下で関数オブジェクトを理解する:
1つの変数の機能:
#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<<"显示整型动态数组:"<<endl;
foe_each(vecIntegers.begin(),vecIntegers.end(),DisplayElement<int>());//函数对象用于了STL算法std::for_each
cout<<"显示字符动态数组:"<<endl;
for_each(listChars.begin(),listChars.end(),DisplayElement<char>());
return 0;
}```
バイナリー機能:
STLのSTDでバイナリ機能を使用する方法::に変換します:
#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;
}