code1
#include <iostream>
#include <queue>
using namespace std;
struct man {
int age;
int h, w;
};
struct compare {
bool operator()(const man &m1, const man &m2) { return m1.age < m2.age; }
};
priority_queue<man, vector<man>, compare> mq;
int main() {
man tmp;
tmp.age = 40;
mq.push(tmp);
tmp.age = 50;
mq.push(tmp);
tmp.age = 30;
mq.push(tmp);
tmp.age = 1;
mq.push(tmp);
while (!mq.empty()) {
cout << mq.top().age << " ";
mq.pop();
}
return 0;
}
code2
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, greater<int>());
cout << "Array after sorting : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
Both two codes above are "fine". My question is about "compare" and "greater<int>()". "compare" is a struct. "greater<int>" is also a struct. Then why "()" is not needed after "compare" but is needed after "greater<int>"?
According to https://cplusplus.com/reference/functional/greater/ , greater is a struct as shown below.
template <class T> struct greater {
bool operator() (const T& x, const T& y) const {return x>y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};