#include "Header.h"
int main()
{
student students[] = {
{87, 10001, "Fred"},
{28, 10002, "Tom"},
{100, 10003, "Alistair"},
{78, 10004, "Sasha"},
};
qsort( students, 4, sizeof(struct student), compare);
for ( int i = 0; i < 4; i++)
cout << students[i].grade << students[i].studentID << students[i].name << endl;
return 0;
}
The error that I get is "No matching function to call for qsort", so I guess it's a problem of the comparator function. Does anybody know why I get this error and what is wrong with my comparator function?
qsort() cannot be used with struct student because it is not trivally-copyable. Why even consider it at all when C++ has the much faster std::sort? (which also can be used with your struct student)
In any case, if you aren't missing #include <cstdlib> , your comparison function needs to take constvoid*, not void* arguments in order for this to compile.
Thanks a ton for your answer, it worked when using const void*.
The reason I used qsort was because it was asked for in the book ( "Think like a programmer" by Anton Spraul) I'm reading. I didn't know about the sort function yet, thanks for the suggestion.
For more information on std::sort() you can check out the tutorial here http://www.cplusplus.com/articles/NhA0RXSz/ which isn't the most in depth one (IE it doesn't go into detail on lambda's, functors and stuff like that but should give you a good grounding to start off with).
I would also highly suggest looking into a better book if your C++ book is suggesting you use qsort() specially when it is a C++ book. Also since it looks like it is teaching C and not C++. Though that is only a suggestion and is quite biased I will admit since I am not really for the whole learn C to learn C++ attitude.
wow that book seriously says "The default fast sort for C/C++ programmers is the qsort function in the standard library"
And it seriously sends structs with std::string members into qsort().
Get rid of it before it's too late.
Well I'm using the book more for the problem solving techniques it offers rather than to learn C++ (I'm using "Accelerated C++" for that purpose) and I think it does a fairly good job at that.