定義一個自定義排序規則的成員函數,然后在類的成員函數中調用
文章目錄
- 1.聲明為static函數
- 2.使用function
- 3.使用匿名函數
1.聲明為static函數
#include <iostream>
#include <algorithm>
#include <list>
class A
{
public:A(){std::list<int> t_list = { 9,8,7,6,5,4,3,2,1 };t_list.sort(compare);for (int i : t_list){std::cout << i << std::endl;}};static bool compare(int x, int y){return x < y;};~A(){};private:};int main()
{A a;return 0;
}
2.使用function
#include <iostream>
#include <algorithm>
#include <list>class A
{
public:A(){std::list<int> t_list = { 9,8,7,6,5,4,3,2,1 };std::function<bool(int,int)> func = std::bind(&A::compare,this,std::placeholders::_1,std::placeholders::_2) ;t_list.sort(func);for (int i : t_list){std::cout << i << std::endl;}};bool compare(int x, int y){return x < y;};~A(){};private:};int main()
{A a;return 0;
}
3.使用匿名函數
#include <iostream>
#include <algorithm>
#include <list>
class A
{
public:A(){std::list<int> t_list = { 9,8,7,6,5,4,3,2,1 };bool(*func)(int, int) = [](int x, int y) { return x < y; };t_list.sort(func);for (int i : t_list){std::cout << i << std::endl;}};~A(){};private:};int main()
{A a;return 0;
}