-1

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;
};
Jason
  • 36,170
  • 5
  • 26
  • 60
  • Same difference than type `int` and value `int{}` (`0`)... You have `std::vector` (and not `std::vector`). – Jarod42 Jul 29 '22 at 09:16
  • Because the template argument must be a type, and the function argument must be a value. – molbdnilo Jul 29 '22 at 09:25
  • [Dupe1](https://stackoverflow.com/questions/18046760/syntax-for-using-stdgreater-when-calling-stdsort-in-c), [Dupe2](https://stackoverflow.com/questions/72451130/why-dont-we-add-parenthesis-when-writing-comparator-in-c), [Dupe3](https://stackoverflow.com/questions/73005801/whats-the-difference-in-comparator-syntax-in-c) – Jason Jul 29 '22 at 09:31

2 Answers2

1

std::greater<int> is a type.

std::greater<int>() is an instance of the type, an object.

The std::sort function needs a callable object, not a type, as function argument in the call.

For std::priority_queue you pass the type as a template argument.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

It's the difference between types and objects.

sort is a function call, and so needs to have an object passed as the third argument. greater<int>() creates a greater<int> object.

But priority_queue<man, vector<man>, compare> mq; is a declaration, so priority_queue<man, vector<man>, compare> is a (template) type, and just needs the type compare as a template argument.

To make a simpler example consider

compare c = compare();

The first compare is the type of the variable c, the second compare creates the object that will be the value of c.

john
  • 85,011
  • 4
  • 57
  • 81