- 函数对象
- 使用函数对象有什么好处
- 解决1-函数指针
- 解决2-函数对象
- 函数对象堆使用
- 函数对象set使用
把有operator()小括号运算符重载函数的对象,称作为函数对象或者仿函数
templatebool compare(T a, T b) { return a > b; } int main() { cout << compare(10, 20) << endl; cout << compare('b', 'y') << endl; }
但是这个函数不灵活,如果要比较小于,如果是库函数,肯定不行。
解决1-函数指针templateinline bool mygreater(T a, T b) { return a > b; } template inline bool myless(T a, T b) { return a < b; } int main() { cout << compare(10, 20, mygreater ()) << endl; cout << compare(10, 20, myless ()) << endl; //cout << compare('b', 'y') << endl; return 0; }
但是这样的问题就是,通过函数指针调用函数,是没有办法内联的,效率很低,因为有函数调用开销。
解决2-函数对象- 通过函数对象调用operator(),可以省略函数的调用开销,比通过函数指针调用函数(不能通过inline内敛调用)效率高
- 因为函数对象是用类生成的,所以可以添加相关的成员变量,用来记录函数对象使用时候更多的信息
template函数对象堆使用class mygreater { public: bool operator()(T a, T b) // 二元函数对象 { return a > b; } }; template class myless { public: bool operator()(T a, T b) // 二元函数对象 { return a < b; } }; // compare是C++的库函数模板 template bool compare(T a, T b, Compare comp) { // 通过函数指针调用函数,是没有办法内联的,效率很低,因为有函数调用开销 return comp(a, b); // operator()(a, b); } int main() { cout << compare(10, 20, mygreater ()) << endl; cout << compare(10, 20, myless ()) << endl; //cout << compare('b', 'y') << endl; return 0; }
int main()
{
priority_queue que1; // vector
for (int i = 0; i < 10; ++i)
{
que1.push(rand() % 100);
}
while (!que1.empty())
{
cout << que1.top() << " ";
que1.pop();
}
cout << endl;
using MinHeap = priority_queue, greater>;
MinHeap que2; // vector
for (int i = 0; i < 10; ++i)
{
que2.push(rand() % 100);
}
while (!que2.empty())
{
cout << que2.top() << " ";
que2.pop();
}
cout << endl;
return 0;
}
函数对象set使用
int main()
{
set> set1;
for (int i = 0; i < 10; ++i)
{
set1.insert(rand() % 100);
}
for (int v : set1)
{
cout << v << " ";
}
cout << endl;
return 0;
}



