[英]functor and function at priority_queue and sort of C++
I try to understand use of functor and function at C++我尝试在 C++ 了解仿函数和 function 的使用
Please see the code below请看下面的代码
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
bool mySort(int a, int b){
if(a > b) return true;
return false;
}
class myClass{
public:
bool operator()(int a, int b){
if(a>b) return true;
return false;
}
};
int main(){
//(1) priority_queue<int, vector<int>, greater<int>> aa;
//(2) priority_queue<int, vector<int>, greater<int>()> bb;
//(3) priority_queue<int, vector<int>, myClass> cc;
//(4) priority_queue<int, vector<int>, mySort> dd;
vector<int> check={1,2,3,4,5,6,7};
//(a) sort(check.begin(), check.end(), mySort);
//(b) sort(check.begin(), check.end(), myClass);
//(c) sort(check.begin(), check.end(), myClass());
return 0;
}
I found only (1),(3) and (a),(c) works.我发现只有 (1),(3) 和 (a),(c) 有效。
What is the difference between function and functor when using sort and priority_queue?使用 sort 和 priority_queue 时 function 和 functor 有什么区别?
I know functor can maintain its state but, this information is not related in this case.我知道仿函数可以维护它的 state 但是,这个信息在这种情况下是不相关的。
I also check sort and priority_queue but fail to understand it.我还检查了sort和priority_queue但无法理解。
Could you help me?你可以帮帮我吗?
When you instantiate a priority_queue
, the third argument must be a type.当你实例化一个
priority_queue
时,第三个参数必须是一个类型。
greater<int>
and myClass
are types; Greater
greater<int>
和myClass
是类型; greater<int>()
and mySort
are not. Greater
greater<int>()
和mySort
不是。
If you create a default priority_queue
, it will default-initialise an ordering of the indicated type.如果您创建默认的
priority_queue
,它将默认初始化指定类型的排序。
priority_queue<int, vector<int>, greater<int>> aa;
is equivalent to相当于
priority_queue<int, vector<int>, greater<int>> aa(greater<int>());
and和
priority_queue<int, vector<int>, myClass> cc;
is equivalent to相当于
priority_queue<int, vector<int>, myClass> cc(myClass());
When you call sort
, you give it a callable object as the third argument, and the template arguments are deduced from the function arguments.当你调用
sort
时,你给它一个可调用的 object 作为第三个参数,并且模板 arguments 是从 ZC1C425268E68385D1AB5074C17A94F14E777DED6 推导出来的。
mySort
and myClass()
are callable objects; mySort
和myClass()
是可调用对象; their types are bool(int,int)
and myClass
, respectively, and these types become the template arguments.它们的类型分别是
bool(int,int)
和myClass
,这些类型成为模板 arguments。
myClass
is a type and can't be used as a function argument. myClass
是一种类型,不能用作 function 参数。
sort(check.begin(), check.end(), mySort);
is equivalent to相当于
sort<vector<int>::iterator, bool(int,int)>(check.begin(), check.end(), mySort);
and和
sort(check.begin(), check.end(), myClass());
is equivalent to相当于
sort<vector<int>::iterator, myClass>(check.begin(), check.end(), myClass());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.