C++笔记-仿函数(functor) 女爷i 2022-10-30 08:23 110阅读 0赞 STL6个组建: 1. 仿函数; 2. 算法; 3. 迭代器; 4. 空间配置器; 5. 容器; 6. 适配器; 仿函数一般不会单独使用,主要是为了搭配STL算法。 函数指针不能满足STL对抽象性的要求,不能满足软件积木的要求,无法和STL其他组建搭配; 本质就是类重载了一个operator(),创建一个行为类似函数的对象。 如下C++容器排序的过程。 程序运行截图都这样: ![20210218144838240.png][] C++排序过程 #include <iostream> #include <algorithm> using namespace std; bool mySort(int a, int b) { return a > b; } void display(int a) { cout << a << " "; } int main() { int arr1[] = { 5, 4, 2, 1, 7, 99 }; sort(arr1, arr1 + 6, mySort); for_each(arr1, arr1 + 6, display); getchar(); return 0; } C++模板 #include <iostream> #include <algorithm> using namespace std; template<class T> inline bool mySort(T const &a, T const &b) { return a > b; } template<class T> inline void display(T const &a) { cout << a << " "; } int main() { int arr1[] = { 5, 4, 2, 1, 7, 99 }; sort(arr1, arr1 + 6, mySort<int>); for_each(arr1, arr1 + 6, display<int>); getchar(); return 0; } 使用C++仿函数来做: #include <iostream> #include <algorithm> using namespace std; struct Sort { bool operator()(int a, int b) { return a < b; } }; struct Display { void operator()(int a) { cout << a << " "; } }; int main() { int arr1[] = { 5, 4, 2, 1, 7, 99 }; sort(arr1, arr1 + 6, Sort()); for_each(arr1, arr1 + 6, Display()); getchar(); return 0; } 使用C++仿函数模版来做: #include <iostream> #include <algorithm> using namespace std; template<class T> struct Sort { bool operator()(T const &a, T const &b) { return a < b; } }; template<class T> struct Display { void operator()(T const &a) { cout << a << " "; } }; int main() { int arr1[] = { 5, 4, 2, 1, 7, 99 }; sort(arr1, arr1 + 6, Sort<int>()); for_each(arr1, arr1 + 6, Display<int>()); getchar(); return 0; } [20210218144838240.png]: /images/20221024/6578b964c3064f05ba47ee8ec08750c4.png
还没有评论,来说两句吧...