如果 sort(A.begin(), A.end(), greater()) 其中 A 是 vector ,您将获得 A 的降序;如果 priority_queue,大于 > Q;你得到 Q 的升序;我不知道为什么,在编写自定义 operator() 时很难记住何时使用 > 何时使用 <。这是我的测试代码:谁能告诉我它们是如何排序的?
struct compare_test{ //similar to greater() in STL
bool operator()(const int a, const int b){
return a>b;
}
};
void my_compare_test(){
vector<int> A;
// priority_queue<int,vector<int>, greater<int> > Q;
priority_queue<int,vector<int>, compare_test > Q;
for (int i = 0; i < 5; i++){
A.push_back(i);
Q.push(i);
}
// sort(A.begin(), A.end(), greater<int>());
sort(A.begin(), A.end(), compare_test()); //get descending order
for (int i = 0; i < 5; i++){
cout << "A = " << A[i] << "; ";
}
cout << endl;
while(!Q.empty()){
cout << "Q = " << Q.top() << "; "; ////get ascending order
Q.pop();
}
cout << endl;
最佳答案
不要认为优先队列是有序的。只需将其视为一种抽象数据类型,它总是让您快速访问“最大元素”。其中“最大元素”定义为包含优先级队列数据的列表中的最后一个元素,前提是该列表使用与优先级队列排序相同的标准进行排序。
那么就没有冲突了。同一个比较器实际上不会以不同的方式对不同的容器进行排序,因为优先级队列没有排序。它有顺序,但未排序。
关于c++ - 为什么 operator() 函数以不同的方式更好地对不同的容器进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16702773/