1

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.

elexhobby
  • 2,588
  • 5
  • 24
  • 33
  • Did you `#include `? – zch Sep 20 '13 at 23:20
  • Yes I have, thanks. The issue was different. All the above piece of code was within main(). But when I removed the class definition outside main, the problem was resolved. I don't understand why though. – elexhobby Sep 20 '13 at 23:26
  • 1
    @elexhobby You should [edit] your question and change it to include this information. – Bernhard Barker Sep 21 '13 at 18:31
  • 1
    possible duplicate of [Why can't a struct defined inside a function be used as functor to std::for\_each?](http://stackoverflow.com/questions/4550914/why-cant-a-struct-defined-inside-a-function-be-used-as-functor-to-stdfor-each) – Oswald Sep 21 '13 at 19:09
  • 1
    You find answers here: [C++ local class as functor](http://stackoverflow.com/q/9772446/237483), [how to define a functor inside a function](http://stackoverflow.com/q/6883892/237483), [Why does this std::sort predicate fail when the class is inside main()?](http://stackoverflow.com/q/6880077/237483) – Christian Ammer Sep 21 '13 at 19:22

1 Answers1

2

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.

Oswald
  • 31,254
  • 3
  • 43
  • 68