Hi,
Can anyone tell me why the following program is giving compiler error when I use a friend function of a class as the comparison predicate for the third parameter of std::sort() algorithm? How to correct it, keep the 'friend' intact?
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
class A {
inline friend bool comp(const A& o1, const A& o2) {
return o1.data < o2.data; // binary predicate function
}
inline friend bool operator < (const A& o1, const A& o2) {
return o1.data < o2.data; // overloaded 'operator < ()' function
}
public:
int data;
A(int i = 0) : data(i) { }
inline int getVal() const { return data; }
};
struct great {
bool operator() (const A& lx, const A& rx) const {
return lx.data < rx.data;
}
};
int main() {
A a(60), b(20), c(50);
std::vector<A> v;
std::list<A> ll;
v.push_back(a);
v.push_back(b);
v.push_back(c);
std::sort(v.begin(), v.end(), comp); // std::sort() called with predicate
std::sort(v.begin(), v.end(), great());
for (vector<A>::const_iterator itr1 = v.begin(); itr1 != v.end(); ++itr1) {
cout << (*itr1).getVal() << endl;
}
ll.push_back(a);
ll.push_back(b);
ll.push_back(c);
ll.sort(); // internally calls overloaded operator < ()
for (list<A>::const_iterator itr2 = ll.begin(); itr2 != ll.end(); ++itr2) {
cout << (*itr2).getVal() << endl;
}
list.sort(comp); // uses predicate in the sort
for (list<A>::const_iterator itr3 = ll.begin(); itr3 != ll.end(); ++itr3) {
cout << (*itr3).getVal() << endl;
}
}