Reputation: 2668
I'm not sure what is wrong with the following code, where I'm trying to sort an array of class objects using a member function comparator.
class Query {
public:
int start;
int end;
int index;
bool operator<(const Query &b) {
return this->start < b.start;
}
};
Query query[q];
for (int i=0;i<q;++i) {
cin>>query[i].start>>query[i].end;
query[i].index = i;
}
sort(query,query+q);
I get the following error:
error: no matching function for call to ‘sort(main()::Query [(((unsigned int)(((int)q) + -0x00000000000000001)) + 1)], main()::Query*)’
Update: I figured out the cause of the error. I had included the class within my main. The problem was resolved when I moved the class definition outside main. I don't have a good enough understanding of C++/OOP to understand why this happens. I'd appreciate if somebody could explain or direct me to helpful resources.
Upvotes: 1
Views: 1642
Reputation: 31685
Local types (i.e. types that are defined inside a function) cannot be used as template arguments in C++03 (one of the template arguments of std::sort()
is the type of the objects that should be sorted). I do not know why C++03 has this restriction. C++11 does not have this restriction anymore.
Upvotes: 2