### help me with functors

Hi, the following is my code, i have two questions:

first, in line 7, why can't i make ba1 and ba2 to be reference?
second, there are some standard comparison functors for sort algorithm, what is the difference between greater<T>() and greater_equal<T>(), and less<T>() and less_equal<T>()?

 ``12345678910111213141516171819202122232425262728`` `````` 1 #include 2 #include "bank_acc.cpp" 3 #include 4 #include 5 using namespace std; 6 7 bool richer (bankAcct ba1, bankAcct ba2){ 8 return ba1.getBalance() > ba2.getBalance(); 9 } 10 11 int main(){ 12 vector baV; 13 14 double balance; 15 for (int i = 1; i <= 5; i++){ 16 cout << "Bank acct No." << i << endl; 17 cout << "Balance: "; 18 cin >> balance; 19 baV.push_back(bankAcct (i, balance)); 20 } 21 22 cout << endl << "Sort bank accts in terms of balance in descending order.\n"; 23 sort(baV.begin(), baV.end(), richer); 24 for (int i = 0; i < baV.size(); i++) 25 cout << baV[i].toString() << endl; 26 27 return 0; 28 }``````
1. of course you can use references:
 ``123`` ``````bool richer (const bankAcct& ba1, const bankAcct& ba2){ return ba1.getBalance() > ba2.getBalance(); }``````

2. greater<T>() sorts in descending order, less<T>() sorts in ascending order and is used by default. less_equal<T>() and greater_equal<T>() are not for use with sort()

Incidentally, #including a cpp file is very strange
Last edited on
I have tried your code, but i get the following compilation error:
`sort_ba.cpp:8:27: error: passing ‘const bankAcct’ as ‘this’ argument of ‘double bankAcct::getBalance()’ discards qualifiers`
Why?
 Why?

Because your forgot to make getBalance() a const member function, as in
`double getBalance() const { return whatever; }`
why must i put 'const' in this case?
Topic archived. No new replies allowed.