定义
如果一个类将()运算符重载为成员函数,这个类就称为函数对象类,这个类的对象就是函数对象。函数对象是一个对象,但是使用的形式看起来像函数调用,实际上也执行了函数调用,因而得名。
函数对象应用实例
#include <iostream>
#include <vector>
#include <numeric> //accumulate 在此头文件定义
using namespace std;
template <class T>
void PrintInterval(T first, T last)
{ //输出区间[first,last)中的元素
for (; first != last; ++first)
cout << *first << " ";
cout << endl;
}
int SumSquares(int total, int value)
{
return total + value * value;
}
template<class T>
class SumPowers
{
private:
int power;
public:
SumPowers(int p) :power(p) { }
const T operator() (const T & total, const T & value)
{ //计算 value的power次方,加到total上
T v = value;
for (int i = 0; i < power - 1; ++i)
v = v * value;
return total + v;
}
};
int main()
{
const int SIZE = 10;
int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vector<int> v(a1, a1 + SIZE);//v初始化
cout << "1) "; PrintInterval(v.begin(), v.end());
int result = accumulate(v.begin(), v.end(), 0, SumSquares);//0 是计算时的初始值
cout << "2) 平方和:" << result << endl;
result = accumulate(v.begin(), v.end(), 0, SumPowers<int>(3));//sumPowers<int>(3) 只是相当于sumPowers类的构造 临时变量
cout << "3) 立方和:" << result << endl;
result = accumulate(v.begin(), v.end(), 0, SumPowers<int>(4));
cout << "4) 4次方和:" << result;
system("pause");
return 0;
}
sort排序
#include <iostream>
#include <vector>
#include <numeric> //accumulate 在此头文件定义
#include<algorithm>
using namespace std;
class T{
public:
T(int age, int score) :m_age(age), m_score(score){}
int m_age;
int m_score;
bool operator>(const T&another)const
{
return this->m_age > another.m_age;
}
void print()
{
cout << "age: " << m_age << "score: " << m_score;
cout << " " << endl;
}
};
bool compare(const T&t1, const T&t2)
{
return t1.m_age > t2.m_age;
}
bool compare1(const T&t1, const T&t2)
{
return t1.operator>(t2);
}
struct Greater{
bool operator()(const T&t1,const T &t2)
{
return t1.m_age > t2.m_age;
}
};
int main()
{
vector <T> v;
for (int i = 0; i < 5; ++i)
{
v.push_back(T(i + 10, i));
}
for (vector<T>::iterator it = v.begin(); it != v.end(); ++it)
{
(*it).print();
}
cout << "____________" << endl;
//sort(v.begin(), v.end(),compare1);
sort(v.begin(), v.end(), Greater());
for (vector<T>::iterator it = v.begin(); it != v.end(); ++it)
{
(*it).print();
}
system("pause");
return 0;
}