函数对象
通过函数指针实现如下功能
#include<iostream>
/*
函数对象=>C语言里面的函数指针
*/
template<typename T>
inline bool myless(T a, T b) //即使这里使用了inline指定为内联,但是在调用compare不是以内联方式展开调用
{
return a < b;
}
template<typename T>
inline bool mygreater(T a, T b)//即使这里使用了inline指定为内联,但是在调用compare不是以内联方式展开调用
{
return a > b;
}
//compare是c++的库函数模板
template<typename T,typename Compare>
bool compare(T a, T b, Compare comp)
{
return comp(a, b);//通过函数指针调用函数,是没有办法内联的,效率很低,因为有函数调用开销
}
int main()
{
std::cout << compare(10, 20, mygreater<int>) << std::endl;
std::cout << compare(10, 20, myless<int>) << std::endl;
}
0
1
通过函数对象实现
#include<iostream>
/*
1.通过函数对象调用operator(),可以省略函数的调用开销,比通过函数指针调用函数(不能够inline内联调用)效率高
2.因为函数对象是用类生成的,所以可以添加相关的成员变量,用来记录函数独享使用时更多的信息
*/
//C++ 函数对象的版本实现
template<typename T>
class mygreater
{
public:
bool operator()(T a, T b)//二元函数对象
{
return a > b;
}
};
template<typename T>
class myless
{
public:
bool operator()(T a, T b)//二元函数对象
{
return a < b;
}
};
//compare是c++的库函数模板
template<typename T,typename Compare>
bool compare(T a, T b, Compare comp)
{
return comp(a, b);
}
int main()
{
std::cout << compare(10, 20, mygreater<int>()) << std::endl;
std::cout << compare(10, 20, myless<int>()) << std::endl;
}
举例标准库中priority_queue优先级队列使用函数对象
#include <iostream>
#include <queue>
int main()
{
std::priority_queue<int> que1;//优先级队列,默认时大根堆实现(适配vector)
for (int i = 0;i < 10;++i)
{
que1.push(rand() % 100);
}
while (!que1.empty())
{
std::cout << que1.top() << " ";
que1.pop();
}
std::cout << std::endl;
using MinHeap = std::priority_queue<int, std::vector<int>, std::greater<int>>;//优先级队列(适配vector),指定小根堆实现(适配vector)
MinHeap que2;//vector
for (int i = 0;i < 10;++i)
{
que2.push(rand() % 100);
}
while (!que2.empty())
{
std::cout << que2.top() << " ";
que2.pop();
}
return 0;
}
输出如下
78 69 67 64 62 58 41 34 24 0
5 27 27 36 42 45 61 81 91 95
例标准库中set使用使用函数对象
#include <iostream>
#include <set>
int main()
{
std::set<int> set1;
for (int i = 0;i < 10;++i)
{
set1.insert(rand() % 100);
}
for (int v : set1)
{
std::cout << v << " " ;
}
std::cout << std::endl;
std::set<int, std::greater<int>> set2;
for (int i = 0;i < 10;++i)
{
set2.insert(rand() % 100);
}
for (int v : set2)
{
std::cout << v << " ";
}
std::cout << std::endl;
return 0;
}
输出信息如下:
0 24 34 41 58 62 64 67 69 78
95 91 81 61 45 42 36 27 5
浙公网安备 33010602011771号